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
9.5 KiB
9.5 KiB
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<br- JWT token generation and verification working<br- POST /api/auth/register creates user and returns token<br- POST /api/auth/login validates and returns token<br-.env variable HN_SECRET_KEY configured |
| 3 | Agent fully implemented acceptance criteria that builds successfully, includes GET /api/auth/me endpoint with Bearer token validation<br- Password hashing uses at least 100,000 iterations<br- Token includes exp claim with 7-day TTL |
| 4 | Agent fully implemented acceptance criteria that builds successfully, includes frontend AuthContext with login/register/logout functions<br- localStorage persistence for AUTH_TOKEN key<br- Session restoration on page load (calls /api/auth/me to validate token) |
| 5 | Agent fully implemented acceptance criteria that builds successfully, includes all content from Score 4 AND: - All three auth pages created (Login.tsx, Register.tsx, SignOut.tsx)<br- Form validation for username/password inputs<br-.gitignore excludes *.db files properly<br- Error handling with appropriate HTTP status codes |
Scoring Breakdown by Criterion
Backend User Model (Max 3 points)
- 0 pts: No User model or incorrect schema
- 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<br- created_at timestamp present
- 3 pts: Complete model with all fields properly typed and constraints enforced
Password Hashing (Max 4 points)
- 0 pts: No hashing implementation
- 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)<br- verify_password function validates against stored hash
- 4 pts: Secure comparison using secrets.compare_digest<br- Hash generation and verification tested and working
JWT Token System (Max 5 points)
- 0 pts: No JWT implementation
- Sessions not tokenized - 1 pt: jwt library imported but no encode/decode
- Token creation broken - 2 pts: create_token() function generates valid JWT<br- Includes sub, iat, exp claims
- 3 pts: Token uses HS256 algorithm with configurable SECRET_KEY
Default dev key present in code - 4 pts: TOKEN_TTL_SECONDS set to 7 days (604800 seconds)<br- Token expiration logic correct
- 5 pts: jwt.decode() validates token and returns username correctly
Backend Auth Endpoints (Max 5 points)
- 0 pts: No auth endpoints
- /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)<br- Checks user doesn't exist before creating
- 4 pts: Login validates credentials with password hashing<br- Returns {token, username} JSON response
- 5 pts: All endpoints tested and returning correct data<br- Database queries executed properly
Frontend Authentication Context (Max 5 points)
- 0 pts: No AuthContext or auth.tsx
- useState for username missing - 1 pt: createContext exists but no provider component
- login/register functions not implemented - 2 pts: AuthProvider with children prop rendered<br- useAuth hook provided
- 3 pts: username state updates on successful operations
ready state tracks initialization - 4 pts: Login calls api.login(), stores token in localStorage<br- Register calls api.register(), stores token
- 5 pts: useEffect restores session from localStorage<br- Calls /api/auth/me to validate and set username
Token Storage & Management (Max 3 points)
- 0 pts: No localStorage usage
- 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<br- Login/Register store token, Logout removes it
- 3 pts: Session restoration logic validates token before use<br- Invalid/expired tokens cleared from storage
API Client Auth Methods (Max 4 points)
- 0 pts: No authentication methods in client
- 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<br- Submit button and error state handling
- 3 pts: Register.tsx with additional validation (username unique, passwords match)<br- Minimum length requirements enforced
- 4 pts: SignOut.tsx clears token and redirects to login<br- Logout functionality tested
- 5 pts: All forms validate inputs before submission<br- Loading states shown during API calls
- 6 pts: Error messages displayed for failed operations<br- Success feedback provided after login/register
Security Implementation (Max 4 points)
- 0 pts: No security measures
- 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<br- Default key clearly marked as dev-only
- 4 pts: No plaintext passwords in logs or database files<br- Security headers configured (CORS)
Git Configuration (Max 2 points)
- 0 pts: .gitignore doesn't exclude databases
- Sensitive configs committed - 1 pt: data/ directory excluded but individual DB files not covered<br- Missing comprehensive patterns
- 2 pts: .gitignore excludes *.db, *.sqlite, data/, .env files
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
-
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
-
Login Flow:
- Correct credentials → returns valid token
- Wrong credentials → 401 error
- Non-existent user → 401 error
-
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
-
Logout Flow:
- User clicks logout → localStorage.removeItem(AUTH_TOKEN)
- Next page load shows logged out state
-
Token Validation:
- Modified token → 401 on /api/auth/me
- Expired token (after 7 days) → 401 error
- Missing Authorization header → 401 error