# M5: Setup Authentication - Score Report **Repository scored:** `../newz` (`/home/daniel/Gitea/daniel/newz`), working tree (auth work is uncommitted) **Rubric:** `milestone/m5-setup-authentication-scoring.md` **Model:** qwen3.5-9b ## Total Score: 31 / 46 (30 base, +1 bonus), assuming the blockers below are fixed **As delivered, the score is 0.** The backend does not start. This matches the rubric's rule that 0 applies when "application won't run". The blockers are listed in the next section. The score above is what the code earns once they are fixed. ## Blockers Found | # | Problem | Where | Evidence | |---|---|---|---| | 1 | `config.py` mixes `model_config` with `class Config` | `backend/config.py` | Carried over from M2. Pydantic v2 raises `PydanticUserError` on import. | | 2 | Circular import between models and database | `backend/app/database.py` imports `Base` from `.models`; `backend/app/models.py` imports `Base` from `.database` | `ImportError: cannot import name 'Base' from partially initialized module 'app.models'` | | 3 | `jwt` (PyJWT) is imported, but `requirements.txt` lists `python-jose` only | `backend/app/auth.py` line 14; `backend/requirements.txt` | `ModuleNotFoundError: No module named 'jwt'` on a clean install | | 4 | Placeholder routes use SQLAlchemy classes as `response_model` | `backend/main.py` `/api/articles`, `/api/authors`, `/api/categories` | `FastAPIError: Invalid args for response field` on import | | 5 | `httpx` is missing (needed by Starlette's `TestClient`) | `backend/requirements.txt` | `RuntimeError: ... requires the httpx2 package` | Blocker 2 also means `Base` used by `app.models` is not the `Base` that `lifespan` calls `create_all` on, so the `users` table would never be created at startup. ## Verification Performed Run in temporary copies. The temp copy was patched step by step so later failures could be seen. Patches were only applied outside the repo. | Step | Result | |---|---| | Clean install of `requirements.txt`, then `import app.models` | Fails on `import jwt`. | | Add PyJWT, fix `config.py` | Fails on the circular import. | | Point `database.py` at `db.session.Base`, add httpx | `main` imports, but the placeholder routes fail (blocker 4). | | Remove the three placeholder `response_model`s | `main` imports. Suite: 8 failed, 9 passed, 9 errors. | | `test_auth.py` | All tests that use the `auth_client` fixture error. Two causes: the temp copy had no `./data/db` directory (`unable to open database file`), and `test_auth.py` never imports `app`, so the fixture would raise `NameError` once the database error was resolved. `test_jwt_token_structure` does not use the fixture. | | Frontend `npm run build` | Fails at `tsc`: 4 `TS6133` errors in `src/tests/*.test.tsx` (unchanged from M3). | | Frontend `npx vite build` | Succeeds. | | Frontend `npx vitest run` | 2 of 2 pass. The tests are still `expect(1).toBe(1)` placeholders. | ## Scoring by Criterion | Criterion | Score | Max | Notes | |---|---|---|---| | Backend User Model | 2 | 3 | Fields are correct: `id`, `username` (String(60), unique, indexed), `password_hash` (String(128)), `created_at`. The model is not usable because of blocker 2, and the `users` table is not registered on the app's `Base`. | | Password Hashing | 3 | 4 | `hash_password` uses PBKDF2-HMAC-SHA256 with 120,000 iterations and a `secrets.token_hex(16)` salt. The stored format is `salt$digest`. `verify_password` uses `secrets.compare_digest`. The hashing test does not run (see above). | | JWT Token System | 4 | 5 | `create_token` sets `sub`, `iat` and `exp` (7 days), signs with HS256, and reads `HN_SECRET_KEY` with a clearly marked dev default. `get_current_user` decodes and checks the user. Deduction: `jwt` is not in requirements (blocker 3). | | Backend Auth Endpoints | 3 | 5 | `POST /api/auth/register` returns 201 with `{token, username}`. `POST /api/auth/login` checks the hash and returns 401 on failure. Deductions: `get_current_user` returns `user.model_dump(...)`, which SQLAlchemy models do not have, so `/api/auth/me` returns 500 for a valid token. Also `logout` requires a token, so an anonymous logout returns 401 (the test expects 204). The duplicate-username check returns 409, while the QA notes say 400. The username regex in `RegisterIn` returns 422 before the 400 check runs. | | Frontend Authentication Context | 3 | 5 | `AuthProvider` provides `username`, `ready`, `login`, `register` and `logout`. `useAuth` is exported. On load it calls `api.me` with the stored token and clears the token on failure. Deduction: `Login.tsx` and `Register.tsx` call `api.login` and `api.register` directly, not the context. They never store the token or set `username`, so after a successful login the app stays on the login screen. | | Token Storage & Management | 2 | 3 | `TOKEN_KEY = 'AUTH_TOKEN'` is used consistently. Logout removes it. Restoration clears invalid tokens. The login and register pages do not store the token (see above). | | API Client Auth Methods | 4 | 4 | `login`, `register`, `logout` and `me` are implemented. `me` sends the Bearer header. Non-OK responses throw. `logout` removes the token even if the request fails. The `TokenResponse` and `MeResponse` types are duplicated in `client.ts` instead of imported from `types/auth.ts`. | | Frontend Auth Pages | 4 | 6 | `Login.tsx` and `Register.tsx` have labelled fields, client-side validation (username pattern, 8-character password, matching passwords), a loading state with a spinner, and error messages. `SignOut.tsx` clears the token and redirects, but **no route points to it** in `App.tsx`. No success feedback is shown. | | Security Implementation | 3 | 4 | PBKDF2 at 120,000 iterations, HS256, `HN_SECRET_KEY` from the environment, and no plaintext passwords. Deduction: no CORS middleware, and `CORS_ORIGINS` in `config.py` is not used. | | Git Configuration | 2 | 2 | `backend/.gitignore` excludes `*.db`, `*.sqlite`, `data/` and `.env`. `data/.gitignore` lists the required patterns. | | **Base total** | **30** | **46** | | ### Bonus - **+1 Input validation and password strength:** awarded. The username regex is `^[a-zA-Z0-9_]{3,20}$` and passwords need at least 8 characters, enforced on both server and client. - **+2 Error messages do not leak and rate-limit placeholders:** not awarded. Login errors are generic, but there are no rate-limit placeholder comments. - **+3 Complete error handling and protected-route redirect:** not awarded. The redirect is implemented, but error handling is incomplete (`/me` returns 500, and the login flow dead-ends). Bonus total: +1. ### Critical Requirements Checklist (from rubric) **Must have for score above 1:** - [x] Passwords never stored as plaintext - [x] PBKDF2 with at least 120,000 iterations (SHA256) - [x] JWT uses HS256 (no `none`) - [x] `HN_SECRET_KEY` used for signing - [x] Token `exp` is 7 days after `iat` **Must have for score above 3:** - [x] Context provides login, register, logout (defined in `auth.tsx`) - [ ] Login and register pages use the context, so `AUTH_TOKEN` is stored on login - [x] Session check on load calls `/api/auth/me` - [ ] `401` on invalid tokens works end to end: `/api/auth/me` returns 500 for a valid token, and that path is not tested Two of the checks marked above 3 fail, so the score-above-3 requirements are not met. ## Other Issues Found 1. **Two model layers.** `backend/models/` (SQLAlchemy `Base` from `db/session.py`) and `backend/app/models.py` (a separate `Base`) both exist. `Article`, `Author` and `Category` are defined in `models/`, and `User` in `app/`. Pick one. 2. **`data/.gitignore` was overwritten.** M4 specified "ignore everything except `keep_files.txt`". M5 replaced it with a pattern list, which removes the M4 rule. The file also has a malformed last line (`# OS specific files.DS_Store`). 3. **`docker-compose.yml` still references `backend-db`.** This is an M4 blocker that remains. The backend also has no healthcheck, but the frontend waits on `service_healthy`. 4. **`M5_AUTH_IMPLEMENTATION.md` overstates the work.** It marks items complete and states that the security checks are satisfied, but the backend does not start and the login page does not complete the flow. Treat it as a plan, not as a test record. 5. **`SignOut.tsx` is unreachable.** Add a `/signout` route, or wire the sign-out button to it. 6. **Frontend build still fails** on the unused test imports (M3 item). ## Path to a Higher Score 1. Remove `class Config` from `config.py`. 2. Break the cycle: have `app/database.py` import `Base` from `db/session.py`, and `app/models.py` use that same `Base`. 3. Add `PyJWT` to `requirements.txt` and remove `python-jose`, or switch the code to `jose`. 4. Remove the `response_model=list[...]` of SQLAlchemy classes on the placeholder routes, or use Pydantic schemas. 5. Add `httpx` to `requirements.txt`. 6. Fix `get_current_user` to return the user object, or a dict built from its fields (`{"username": user.username}`), not `model_dump`. 7. Make `Login.tsx` and `Register.tsx` call `useAuth().login` and `useAuth().register`. 8. Add `from main import app` to `test_auth.py`, and make the tests create `./data/db` before running. 9. Route `SignOut.tsx`, and make `logout` accept anonymous calls (return 204 without a token). 10. Fix the frontend `tsc` errors so `npm run build` passes.