From c1313c8758ed1e6aa598cd7423eaed40db84bc06 Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Thu, 29 Oct 2026 16:17:14 +0000 Subject: [PATCH] feat: add M5 setup authentication milestone based on reference implementation Backend (FastAPI): - User model with username, password_hash, created_at fields - PBKDF2 password hashing (120,000 iterations with salt) - JWT token generation using HS256 algorithm (7-day expiry) - Auth endpoints: POST /api/auth/register, POST /api/auth/login - GET /api/auth/me validates Bearer tokens - Environment variable HN_SECRET_KEY for JWT signing Frontend (React + TypeScript): - AuthContext for authentication state management - Login.tsx, Register.tsx, SignOut.tsx pages - AUTH_TOKEN stored in localStorage - Session restoration on page load - API client with auth methods and token attachment Security: - Passwords hashed with PBKDF2-SHA256 (not plaintext) - Random salt per password using secrets.token_hex - JWT signed with configurable SECRET_KEY - 401 responses for invalid/expired tokens Reference implementation used: /home/daniel/Gitea/daniel/news --- README.md | 15 +- milestone/m5-setup-authentication-prompt.md | 489 +++++++++++++++++++ milestone/m5-setup-authentication-scoring.md | 148 ++++++ 3 files changed, 651 insertions(+), 1 deletion(-) create mode 100644 milestone/m5-setup-authentication-prompt.md create mode 100644 milestone/m5-setup-authentication-scoring.md diff --git a/README.md b/README.md index c5d146b..4d082b8 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,17 @@ This benchmark consists of multiple milestones, each representing a separate tas - [M2 - Setup Backend](milestone/m2-setup-backend-prompt.md) - [M2 - Setup Backend Scoring](milestone/m2-setup-backend-scoring.md) +### M3: Frontend Application +This benchmark consists of multiple milestones, each representing a separate task: + +### M1: Git Repository Setup +- [M1 - Setup Git Project](milestone/m1-setup-git-project-prompt.md) +- [M1 - Setup Git Project Scoring](milestone/m1-setup-git-project-scoring.md) + +### M2: Backend Infrastructure +- [M2 - Setup Backend](milestone/m2-setup-backend-prompt.md) +- [M2 - Setup Backend Scoring](milestone/m2-setup-backend-scoring.md) + ### M3: Frontend Application - [M3 - Setup Frontend](milestone/m3-setup-frontend-prompt.md) - [M3 - Setup Frontend Scoring](milestone/m3-setup-frontend-scoring.md) @@ -43,7 +54,9 @@ This benchmark consists of multiple milestones, each representing a separate tas - [M4 - Setup Developer Environment](milestone/m4-setup-developer-environment-prompt.md) - [M4 - Setup Developer Environment Scoring](milestone/m4-setup-developer-environment-scoring.md) -## Context Management +### M5: Authentication System +- [M5 - Setup Authentication](milestone/m5-setup-authentication-prompt.md) +- [M5 - Setup Authentication Scoring](milestone/m5-setup-authentication-scoring.md) After each milestone the agents context MUST be cleared. This tests the models reasoning capabilities and how it performs with incomplete information. diff --git a/milestone/m5-setup-authentication-prompt.md b/milestone/m5-setup-authentication-prompt.md new file mode 100644 index 0000000..4922a9f --- /dev/null +++ b/milestone/m5-setup-authentication-prompt.md @@ -0,0 +1,489 @@ +# M5: Setup Authentication + +## Prompt + +Implement complete authentication for **newzy** news web application. Follow the reference implementation pattern from `/home/daniel/Gitea/daniel/news`. + +### Backend Requirements (FastAPI) + +1. Create `backend/app/auth.py` with: + - Password hashing using PBKDF2 with salt + - JWT token creation and verification + - Current user dependency that validates Bearer tokens + - Environment variable `HN_SECRET_KEY` for JWT signing (default dev key) + +2. Update `backend/app/models.py` to add User model: + - `id`: Integer primary key + - `username`: String(60), unique, index + - `password_hash`: String(128) + - `created_at`: DateTime with default + +3. Create/update authentication endpoints in `backend/app/main.py`: + - `POST /api/auth/register` - Register new user, return JWT token + - `POST /api/auth/login` - Login, return JWT token + - `POST /api/auth/logout` - Logout (clear token, optional) + - `GET /api/auth/me` - Return current user info + - Password hashing with PBKDF2 (120,000 iterations minimum) + +4. Create/update `backend/requirements.txt`: + - Add `python-jose[cryptography]` for JWT + - Add `passlib[bcrypt]` or hashlib for password hashing + - Ensure all auth dependencies are listed + +5. Update `backend/app/database.py` if needed: + - Configure SQLite database properly for user persistence + - Ensure models can be created/queried + +6. Create `data/.gitignore` with patterns to exclude: + ```python + *.db + *.sqlite + data.db + newzy.db + ``` + +7. Update project root `docker-compose.yml` if needed: + - Add environment variable override for `HN_SECRET_KEY` (optional, default in code) + - Ensure database volume is properly mounted + +### Frontend Requirements (React + TypeScript) + +1. Create `frontend/src/types/auth.ts`: + ```typescript + export interface TokenResponse { + token: string; + username: string; + } + + export interface MeResponse { + username: string; + } + ``` + +2. Update `frontend/src/api/client.ts`: + - Add methods for auth endpoints: `login(username, password)`, `register(username, password)`, `logout()`, `me()` + - Implement JWT token attachment to requests (Authorization: Bearer ) + - Handle token storage in localStorage + +3. Create `frontend/src/auth.tsx`: + - Create AuthContext with username and ready state + - Provide login, register, logout functions + - On app load, check localStorage for token and call `/api/auth/me` to restore session + - If token invalid/expired, clear storage + - Export `AuthProvider` component + +4. Create page components: + - `frontend/src/pages/Login.tsx`: Login form with username/password validation + - `frontend/src/pages/Register.tsx`: Registration form with username/password validation + - `frontend/src/pages/SignOut.tsx`: Sign out button that clears token and redirects to login + +5. Update `frontend/src/App.tsx`: + - Wrap app with `` + - Set up protected routes for logged-in users (optional placeholder) + +6. Create CSS styling: + - `frontend/src/assets/styles/auth.css` or include in existing styles + - Auth pages should be clean, accessible forms + - Proper loading states during API calls + +### Shared Requirements + +1. Token Management: + - JWT token stored in `localStorage` with key `AUTH_TOKEN` + - Tokens have 7-day expiry (7 * 24 * 60 * 60 seconds) + - Token format: `sub=USERNAME, iat=TIMESTAMP, exp=TIMESTAMP+7days` + +2. Security: + - Passwords hashed with PBKDF2-HMAC-SHA256 (120,000 iterations minimum) + - Salt generated using `secrets.token_hex(16)` for uniqueness + - JWT signed with HS256 algorithm + - Bearer token in Authorization header: `Authorization: Bearer ` + +3. Error Handling: + - 401 on invalid/expired token + - Clear error messages for user actions + - Best effort logout on client side + +### Testing Requirements (M3 already covers this) +- Unit tests for auth functions +- E2E tests for login/register/logout flows + +Remember: Focus ONLY on authentication setup. No complex UI features or business logic required beyond auth endpoints and pages. Use the reference implementation in `/home/daniel/Gitea/daniel/news` as a guide for patterns and structure. + +## Description + +This milestone implements complete JWT-based authentication for newzy news application using FastAPI backend with PBKDF2 password hashing and React frontend with localStorage token management. The scope includes user registration, login, logout, and session restoration—no complex UI features beyond authentication pages. + +**Purpose**: Enable secure user accounts with JWT tokens for protecting content creation and interaction operations in subsequent milestones. + +**Target Audience**: Developers who need to understand the auth flow and extend it with features like profile management or social login. + +**Expected Outcomes**: A fully functional authentication system where users can register, log in, receive JWT tokens, and maintain session state across page reloads. Backend validates tokens against user records. Frontend manages token storage and applies to API requests automatically. + +## Acceptance Criteria + +- [ ] User model created with username, password_hash, created_at fields +- [ ] Password hashing implemented with PBKDF2 (120,000+ iterations) +- [ ] JWT token generation using HS256 algorithm with 7-day expiry +- [ ] POST /api/auth/register accepts username/password, returns token +- [ ] POST /api/auth/login accepts credentials, returns token +- [ ] POST /api/auth/logout clears state (client-side best effort) +- [ ] GET /api/auth/me validates Bearer token, returns current user +- [ ] Frontend auth.tsx with AuthContext for state management +- [ ] Auth pages: Login.tsx, Register.tsx, SignOut.tsx created +- [ ] API client includes auth methods with token attachment +- [ ] localStorage persistence for AUTH_TOKEN key +- [ ] Session restoration on page load (check token validity) +- [ ] Token stored in localStorage expires automatically after 7 days +- [ ] 401 responses for invalid/missing/expired tokens +- [ ] .gitignore excludes database files and sensitive configs + +## Technical Details + +### Backend User Model + +```python +# backend/app/models.py + +from datetime import datetime +from sqlalchemy import DateTime, ForeignKey, Integer, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +class User(Base): + __tablename__ = "users" + + id: Mapped[int] = mapped_column(primary_key=True) + username: Mapped[str] = mapped_column(String(60), unique=True, index=True) + password_hash: Mapped[str] = mapped_column(String(128)) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) +``` + +### Password Hashing (PBKDF2) + +```python +# backend/app/auth.py + +import hashlib +import secrets +from typing import Optional + +PBKDF2_ITERATIONS = 120_000 + +def hash_password(password: str) -> str: + """Generate password hash with random salt.""" + salt = secrets.token_hex(16) + digest = hashlib.pbkdf2_hmac( + "sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS + ).hex() + return f"{salt}${digest}" + +def verify_password(password: str, stored: str) -> bool: + """Verify password against stored hash.""" + try: + salt, digest = stored.split("$", 1) + except ValueError: + return False + + candidate = hashlib.pbkdf2_hmac( + "sha256", password.encode(), bytes.fromhex(salt), PBKDF2_ITERATIONS + ).hex() + + return secrets.compare_digest(candidate, digest) +``` + +### JWT Token Creation & Verification + +```python +# backend/app/auth.py + +import jwt +import os +from fastapi import Depends, HTTPException +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer + +SECRET_KEY = os.environ.get("HN_SECRET_KEY", "hn-clone-dev-secret-change-me") +ALGORITHM = "HS256" +TOKEN_TTL_SECONDS = 7 * 24 * 60 * 60 # 7 days + +_bearer = HTTPBearer(auto_error=False) + +def create_token(username: str) -> str: + """Create JWT token for user.""" + now = int(time.time()) + payload = { + "sub": username, + "iat": now, + "exp": now + TOKEN_TTL_SECONDS + } + return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) + +def get_current_user( + credentials: Optional[HTTPAuthorizationCredentials] = Depends(_bearer), + db: Session = Depends(get_db), +) -> dict: + """Validate Bearer token and return user data.""" + if credentials is None: + raise HTTPException(status_code=401, detail="Not authenticated") + + try: + payload = jwt.decode( + credentials.credentials, SECRET_KEY, algorithms=[ALGORITHM] + ) + except jwt.PyJWTError as e: + raise HTTPException(status_code=401, detail="Invalid or expired token") + + username = payload.get("sub") + user = db.query(User).filter(User.username == username).first() + + if not user: + raise HTTPException(status_code=401, detail="Unknown user") + + return user +``` + +### Authentication Endpoints (FastAPI) + +```python +# backend/app/main.py + +@app.post("/api/auth/register", response_model=dict) +async def register(username: str, password: str): + """Register new user.""" + # Validate username (alphanumeric, 3-20 chars) + if not re.match(r'^[a-zA-Z0-9_]{3,20}$', username): + raise HTTPException(status_code=400, detail="Invalid username") + + # Check user doesn't exist + existing = db.query(User).filter(User.username == username).first() + if existing: + raise HTTPException(status_code=400, detail="Username already exists") + + # Create user with hashed password + new_user = User( + username=username, + password_hash=hash_password(password) + ) + db.add(new_user) + db.commit() + + # Return JWT token + return { + "token": create_token(username), + "username": username + } + +@app.post("/api/auth/login", response_model=dict) +async def login(username: str, password: str): + """Authenticate and return JWT token.""" + user = db.query(User).filter(User.username == username).first() + if not user or not verify_password(password, user.password_hash): + raise HTTPException(status_code=401, detail="Invalid credentials") + + return { + "token": create_token(username), + "username": username + } + +@app.get("/api/auth/me", response_model=dict) +async def get_current_user_info(user: dict = Depends(get_current_user)): + """Return current user data.""" + return {"username": user.username} + +@app.post("/api/auth/logout", status_code=204) +async def logout(): + """Logout (stateless - token discarded on client side).""" + pass # Optional: server-side invalidation if needed +``` + +### Frontend Auth Context + +```typescript +// frontend/src/auth.tsx + +interface TokenResponse { + token: string; + username: string; +} + +const TOKEN_KEY = "AUTH_TOKEN"; + +export interface AuthState { + username: string | null; + ready: boolean; + login: (username: string, password: string) => Promise; + register: (username: string, password: string) => Promise; + logout: () => void; +} + +const AuthContext = createContext(null); + +export function AuthProvider({ children }: { children: ReactNode }) { + const [username, setUsername] = useState(null); + const [ready, setReady] = useState(false); + + // Restore session on load + useEffect(() => { + const stored = localStorage.getItem(TOKEN_KEY); + if (!stored) { + setReady(true); + return; + } + + api.me(stored) + .then((user) => setUsername(user.username)) + .catch(() => localStorage.removeItem(TOKEN_KEY)) + .finally(() => setReady(true)); + }, []); + + const login = useCallback(async (username: string, password: string) => { + const res = await api.login(username, password); + localStorage.setItem(TOKEN_KEY, res.token); + setUsername(res.username); + }, [api]); + + const register = useCallback(async (username: string, password: string) => { + const res = await api.register(username, password); + localStorage.setItem(TOKEN_KEY, res.token); + setUsername(res.username); + }, [api]); + + const logout = useCallback(() => { + // Best effort logout + api.logout().catch(() => {}); + localStorage.removeItem(TOKEN_KEY); + setUsername(null); + }, [api]); + + return ( + + {children} + + ); +} +``` + +### API Client with Auth Methods + +```typescript +// frontend/src/api/client.ts + +export const api = { + async login(username: string, password: string): Promise { + const res = await fetch('/api/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }) + }); + + if (!res.ok) throw new Error('Login failed'); + return res.json(); + }, + + async register(username: string, password: string): Promise { + const res = await fetch('/api/auth/register', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }) + }); + + if (!res.ok) throw new Error('Registration failed'); + return res.json(); + }, + + async me(token: string): Promise<{ username: string }> { + const res = await fetch('/api/auth/me', { + headers: { Authorization: `Bearer ${token}` } + }); + + if (!res.ok) throw new Error('Invalid token'); + return res.json(); + }, + + async logout(): Promise { + try { + await fetch('/api/auth/logout', { method: 'POST' }); + } catch (e) { + // Best effort - discard token anyway + } + }, + + // Other API methods with token attachment... +}; +``` + +### Login/Register Pages Structure + +**Login.tsx:** +- Form with username and password fields +- Submit button with loading state +- Validation for empty/invalid inputs +- Redirect to dashboard after successful login + +**Register.tsx:** +- Form with username, password, confirm password fields +- Validation: unique username, matching passwords, minimum lengths +- Error messages for existing usernames or weak passwords +- Redirect to login after successful registration + +### Security Configuration + +```python +# .env.example (project root) + +HN_SECRET_KEY=your-secret-key-change-in-production +``` + +**Important**: Change `HN_SECRET_KEY` in production! Default dev key should never be used. + +## QA Notes + +### Testing Checklist - Backend +- [ ] User registration creates account with hashed password +- [ ] Duplicate username rejection with 400 status +- [ ] Login validates credentials and returns token +- [ ] Invalid credentials return 401 +- [ ] JWT token has correct expiry (7 days) +- [ ] Token verification checks against database +- [ ] Unknown user on /api/auth/me returns 401 +- [ ] Missing/expired Bearer token returns 401 + +### Testing Checklist - Frontend +- [ ] AuthContext provides login, register, logout functions +- [ ] localStorage persists AUTH_TOKEN correctly +- [ ] Session restores on page load (validates token) +- [ ] Invalid token cleared from storage on error +- [ ] Login form validates inputs before submission +- [ ] Register form checks username uniqueness +- [ ] Protected routes redirect unauthenticated users to login +- [ ] Logout clears token and navigates to login + +### Security Review Checklist +- [x] Passwords never stored as plaintext +- [x] JWT signed with strong secret (not hardcoded) +- [x] PBKDF2 iterations >= 120,000 +- [x] Salt generated per-password using secrets module +- [x] Username validation prevents injection attacks +- [x] Token expiry set to prevent session hijacking +- [ ] CSRF protection not needed (stateless auth) + +### Performance Considerations +- JWT creation should be fast (<1ms) +- Password hashing takes ~100-200ms (PBKDF2) - acceptable for login +- Database queries cached where possible +- Frontend token storage doesn't impact performance + +### Known Issues / Limitations +- PBKDF2 is slower than bcrypt - may need async handling +- JWT tokens don't expire until 7 days (no refresh tokens) +- No rate limiting on auth endpoints yet +- Password reset not implemented +- Email verification not implemented +- Account locking after failed attempts not implemented + +### Success Metrics +- Registration complete in <2 seconds with validation feedback +- Login completes in <500ms (excluding network) +- JWT token format valid and decodable +- Session persists across browser restarts within 7 days +- Security headers present (CORS configured appropriately) +- No plaintext passwords in database or logs diff --git a/milestone/m5-setup-authentication-scoring.md b/milestone/m5-setup-authentication-scoring.md new file mode 100644 index 0000000..1ec74d2 --- /dev/null +++ b/milestone/m5-setup-authentication-scoring.md @@ -0,0 +1,148 @@ +# M5: Setup Authentication - Scoring Rubric + +## Acceptance Criteria Scoring Table + +| Score | Criteria | +|-------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| 0 | Agent failed to implement acceptance criteria:
- No User model created
- Password hashing not implemented (plaintext storage)
- JWT not generated/verified
- Auth endpoints missing or non-functional
- Frontend auth.tsx absent | +| 1 | Agent partially implemented acceptance criteria that builds successfully:
- Basic User model but no password hashing
- Single auth endpoint working (register OR login only)
- Token created but not stored/attached properly
- No frontend AuthContext | +| 2 | Agent fully implemented acceptance criteria that builds successfully:
- User model with username, password_hash fields
- PBKDF2 password hashing implemented with salt- All three auth pages created (Login.tsx, Register.tsx, SignOut.tsx)- Missing required fields +- **1 pt**: User model created but only has id and username
- password_hash field missing +- **2 pts**: User model with id, username (unique+indexed), password_hash fields- Plaintext passwords stored +- **1 pt**: Weak hashing algorithm (<8 iterations)
- Fixed salt for all users +- **2 pts**: PBKDF2 or bcrypt implemented with >=100,000 iterations
Random salt per password (secrets.token_hex) +- **3 pts**: Hash format correct (salt$digest)- Sessions not tokenized +- **1 pt**: jwt library imported but no encode/decode
- Token creation broken +- **2 pts**: create_token() function generates valid JWTDefault dev key present in code +- **4 pts**: TOKEN_TTL_SECONDS set to 7 days (604800 seconds)- /api/auth/* routes missing +- **1 pt**: Only one endpoint implemented
- Register OR login working, not both +- **2 pts**: Both register and login POST endpoints functional
Correct status codes (200, 400, 401) +- **3 pts**: Register validates username format (alphanumeric)- useState for username missing +- **1 pt**: createContext exists but no provider component
- login/register functions not implemented +- **2 pts**: AuthProvider with children prop rendered ready state tracks initialization +- **4 pts**: Login calls api.login(), stores token in localStorage- Token never stored client-side +- **1 pt**: TOKEN_KEY constant defined but inconsistent
Mixed case keys in storage +- **2 pts**: AUTH_TOKEN key used consistently across frontend code- Fetch calls don't include tokens +- **1 pt**: api.login() and api.register() functions exist
Basic fetch implementations +- **2 pts**: api.me(token) includes Bearer Authorization header
Token passed correctly +- **3 pts**: api.logout() clears token from localStorage
Best effort attempt on server logout +- **4 pts**: All auth methods error-handled properly
Throw errors on 401/400 responses + +### Frontend Auth Pages (Max 6 points) +- **0 pts**: No Login/Register pages
- SignOut component missing +- **1 pt**: Only Login.tsx created
No registration option +- **2 pts**: Login.tsx with username/password form fields- Plaintext passwords or exposed tokens +- **1 pt**: Password hashing present but weak algorithm
- <50,000 iterations +- **2 pts**: PBKDF2 with correct salt generation
HS256 algorithm used for JWT +- **3 pts**: SECRET_KEY configurable via environment variable- Sensitive configs committed +- **1 pt**: data/ directory excluded but individual DB files not covered Best practices followed + +## Total Possible Score: 46 points + +## Evaluation Notes +- Partial credit given for incomplete but working implementations (Score 1) +- Full credit requires all acceptance criteria met with passing verification (Score 2 minimum) +- Higher scores require additional value-add content beyond baseline requirements +- Score 0 indicates agent did not attempt the task or security is compromised + +## Critical Security Requirements + +**MUST HAVE for Score >1:** +- [ ] Passwords NEVER stored as plaintext +- [ ] PBKDF2 with >=100,000 iterations (SHA256) +- [ ] JWT uses HS256 algorithm (never none or symmetric without secret) +- [ ] HN_SECRET_KEY used for signing tokens +- [ ] Token includes exp claim set to 7 days from iat + +**MUST HAVE for Score >3:** +- [ ] AuthContext provides login, register, logout functions +- [ ] localStorage persistence with AUTH_TOKEN key +- [ ] Session validation on page load (calls /api/auth/me) +- [ ] 401 responses for invalid tokens + +## Bonus Points Consideration + +**+1 point** for: +- Input validation regex in register endpoint (username: ^[a-zA-Z0-9_]{3,20}$) +- Password strength requirements enforced (minimum length, complexity) + +**+2 points** for: +- Error messages don't leak information (e.g., "Invalid credentials" not "User doesn't exist") +- Rate limiting placeholder comments in auth endpoints + +**+3 points** for: +- Complete error handling with meaningful user feedback +- Protected routes redirect to login (frontend guard) + +## Test Scenarios to Verify Score 5 + +1. **Registration Flow**: + - New username + password → creates User record with hashed password + - Returns {token, username} in response + - Token can be used for /api/auth/me and returns user data + +2. **Login Flow**: + - Correct credentials → returns valid token + - Wrong credentials → 401 error + - Non-existent user → 401 error + +3. **Session Restoration**: + - Page load with stored AUTH_TOKEN → calls /api/auth/me + - Valid token → username set in state + - Invalid/expired token → localStorage cleared, ready=true + +4. **Logout Flow**: + - User clicks logout → localStorage.removeItem(AUTH_TOKEN) + - Next page load shows logged out state + +5. **Token Validation**: + - Modified token → 401 on /api/auth/me + - Expired token (after 7 days) → 401 error + - Missing Authorization header → 401 error