Mirrored from https://github.com/davoodmehraban89/Aram.git
Synced Dec 4, 15:30 UTC
dependabot/npm_and_yarn/frontend/globals-17.15.0
add-index-html-10623938925177053894
arena/094f314c-aram
arena/2d4eda07-aram
chatgpt-phase1b2-autopilot
codex/adr-future-connectors-pi-v1
codex/aram-account-note-source-trace-20261031
codex/aram-actions-node24-maintenance-20261031
codex/aram-analyst-review-workbook-20261031
codex/aram-bs-candidate-statement-20261031
codex/aram-cash-flow-direct-candidate-20261031
codex/aram-clean-reference-year-integrity-20261030
codex/aram-cross-statement-controls-20261031
codex/aram-equity-changes-candidate-20261031
codex/aram-five-statement-cli-20261031
codex/aram-five-statement-integration-20261031
codex/aram-five-statement-orchestrator-20261031
codex/aram-gate3-coverage-target-guard-20261030
codex/aram-gate3-hidden-xlsx-guard-20261030
codex/aram-gate3-integration-validation-20261030
codex/aram-gate3-mapping-change-preview-20261030
codex/aram-gate3-stale-note-guard-20261030
codex/aram-income-statement-candidate-20261031
codex/aram-manifest-referential-integrity-20261031
codex/aram-mapping-source-parser-20261101
codex/aram-multidimensional-mapping-20261101
codex/aram-multistatement-mapping-20261031
codex/aram-pipeline-manifest-schema-20261031
codex/aram-readonly-mapping-coverage-20261031
codex/aram-reconciliation-review-gate-20261031
codex/aram-same-flush-fiscal-lock-20261030
codex/aram-synthetic-windows-demo-20261031
codex/aram-trial-balance-diagnostic-20261031
codex/aram-windows-background-detail-search-20261031
codex/aram-windows-detail-review-20261031
codex/aram-windows-five-statement-pilot-20261031
codex/aram-windows-statement-figures-20261031
codex/gate-2a-pilot-workbook
codex/gate-2a-pilot-workbook-6864754244772568979
codex/gate3-authenticated-principal-boundary-20261030
codex/gate3-authored-draft-staging-20261030
codex/gate3-carry-forward-preview-20261023
codex/gate3-draft-staging-audit-20261030
codex/gate3-mapping-batch-freshness-20261030
codex/gate3-mapping-batch-review-20261030
codex/gate3-mapping-core
codex/gate3-mapping-coverage-20261023
codex/gate3-mapping-excel-20261023
codex/gate3-note-mapping-review-20261023
codex/gate3-signed-year-scope-20261030
codex/gate3-unapproved-proposal-storage-20261030
codex/payvast-mapping-discovery-20261023
codex/phase-2a-backend-foundation
codex/phase-2b-post-merge-record
codex/phase-2b-source-registration
codex/phase-2b-source-registration-12955190277775369594
codex/post-gate2a-control-reconciliation
codex/post-pr18-acceptance-record
codex/project-control-foundation
codex/t1-repo-hygiene-20261023
codex/t2-ci-hardening-20261023
codex/t3-explicit-migrations-20261023
codex/t6a-readonly-diagnostics-20261023
codex/v1-01-safety-gate-hardening
codex/v1-year-isolation-followup-20261023
codex/windows-native-pilot-shell-20261030
dependabot/github_actions/actions/checkout-7
dependabot/github_actions/actions/setup-node-6
dependabot/github_actions/actions/setup-python-7
dependabot/github_actions/actions/upload-artifact-7
dependabot/npm_and_yarn/frontend/eslint-plugin-react-hooks-7.1.1
dependabot/npm_and_yarn/frontend/globals-17.15.0
dependabot/npm_and_yarn/frontend/vite-8.4.0
dependabot/npm_and_yarn/frontend/vitest-5.1.2
dependabot/npm_and_yarn/frontend/vitest/coverage-v8-5.1.2
dependabot/pip/backend/mypy-gte-1.13-and-lt-3
dependabot/pip/backend/pytest-cov-gte-6.0-and-lt-8
dependabot/pip/backend/setuptools-gte-75-and-lt-85
docs/aram-master-control-plan-20261111
docs/aram-roadmap-dashboard-20261030
docs/financial-statement-reconciliation-1402-1404-20261110
feat/gate3-governed-mapping-20261101
feat/gate3-package9-1-security-20261103
feat/gate3-package9-isolated-20261103
fix/password-unicode-validation-20261111
governance/aram-5-1-3-controls-20261030
governance/role-based-operating-model
jules-1168663913887856558-73b8a885
jules-gate-2b-mapping-workflow-foundation-4137724387867065330
phase-1b1-audit-report-7365389436990903239
phase-2a-backend-foundation-10237597358138521261
phase1b2-postmerge-metadata-fix
refactor/drg-parent-year-id-15088443704684163304
source-data-cleanup
| 1 | """R1 (booklet 2.1) — real authentication: acceptance evidence. |
| 2 | |
| 3 | Every test here maps to a line of the R1 acceptance table in the PR report: |
| 4 | forged actor, missing token, wrong role, hashed-only storage, expiry, logout, |
| 5 | lockout, PBKDF2 work factor, backup confinement, and the desktop one-time token. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import sqlite3 |
| 11 | from datetime import UTC, datetime, timedelta |
| 12 | |
| 13 | import pytest |
| 14 | from fastapi.testclient import TestClient |
| 15 | from pydantic import BaseModel |
| 16 | |
| 17 | from aram_backend.auth import LaunchGuard |
| 18 | from aram_backend.database import get_session |
| 19 | from aram_backend.desktop import create_desktop_app, initialize_database |
| 20 | from aram_backend.main import app as main_app |
| 21 | from aram_backend.models import AuthSession, User, UserRole |
| 22 | from aram_backend.services.backup import BackupError, confine_dest, create_backup |
| 23 | from aram_backend.services.users import ( |
| 24 | MAX_FAILED_LOGINS, |
| 25 | PBKDF2_ROUNDS, |
| 26 | AuthenticationError, |
| 27 | UserError, |
| 28 | authenticate, |
| 29 | create_user, |
| 30 | hash_password, |
| 31 | issue_session, |
| 32 | resolve_session, |
| 33 | set_active, |
| 34 | token_hash, |
| 35 | ) |
| 36 | from conftest import login, make_user |
| 37 | |
| 38 | # Routes that must work before a session exists — and nothing else. |
| 39 | PUBLIC = {("GET", "/api/v1/health"), ("POST", "/api/v1/auth/login"), ("POST", "/api/v1/auth/launch")} |
| 40 | |
| 41 | |
| 42 | def _all_routes(routes): |
| 43 | """Flatten included routers (this FastAPI wraps them in _IncludedRouter).""" |
| 44 | from fastapi.routing import APIRoute |
| 45 | |
| 46 | for route in routes: |
| 47 | if isinstance(route, APIRoute): |
| 48 | yield route |
| 49 | elif hasattr(route, "original_router"): |
| 50 | yield from _all_routes(route.original_router.routes) |
| 51 | elif hasattr(route, "routes"): |
| 52 | yield from _all_routes(route.routes) |
| 53 | |
| 54 | |
| 55 | def _db(api_client): |
| 56 | """Borrow a session from the app's overridden dependency (test-only).""" |
| 57 | override = api_client.app.dependency_overrides[get_session] |
| 58 | generator = override() |
| 59 | return next(generator), generator |
| 60 | |
| 61 | |
| 62 | # ------------------------------------------------------- forged actor / 401 |
| 63 | def test_forged_actor_admin_without_a_session_is_rejected(anon_client): |
| 64 | """The headline R1 attack: claim to be admin in the body, send no token.""" |
| 65 | year = anon_client.post("/api/v1/years/1/approve", json={"actor": "admin"}) |
| 66 | assert year.status_code == 401 |
| 67 | assert anon_client.post("/api/v1/years/1/lock", json={"actor": "admin"}).status_code == 401 |
| 68 | assert anon_client.post("/api/v1/backup", json={"dest": "b", "actor": "admin"}).status_code == 401 |
| 69 | assert anon_client.get("/api/v1/users?actor=admin").status_code == 401 |
| 70 | |
| 71 | |
| 72 | def test_forged_actor_admin_with_a_preparer_session_is_forbidden(api_client): |
| 73 | """A real but low-privileged session cannot escalate by naming an admin.""" |
| 74 | token = make_user(api_client, "prep", "preparer") |
| 75 | headers = {"Authorization": f"Bearer {token}"} |
| 76 | r = api_client.post("/api/v1/years/1/approve", json={"actor": "root"}, headers=headers) |
| 77 | assert r.status_code == 403 |
| 78 | r = api_client.post("/api/v1/backup", json={"dest": "b", "actor": "root"}, headers=headers) |
| 79 | assert r.status_code == 403 |
| 80 | r = api_client.get("/api/v1/users", headers=headers) |
| 81 | assert r.status_code == 403 |
| 82 | |
| 83 | |
| 84 | def test_every_route_except_the_public_three_requires_a_session(api_client): |
| 85 | """No endpoint was forgotten: enumerate the real app and probe each one.""" |
| 86 | api_client.headers.pop("Authorization", None) |
| 87 | checked = 0 |
| 88 | for route in _all_routes(main_app.routes): |
| 89 | path = route.path |
| 90 | if not path.startswith("/api/"): |
| 91 | continue |
| 92 | for method in sorted(route.methods - {"HEAD", "OPTIONS"}): |
| 93 | if (method, path) in PUBLIC: |
| 94 | continue |
| 95 | url = path |
| 96 | for name in ("year_id", "note_id", "mapping_id", "line_id", "request_id", "username"): |
| 97 | url = url.replace("{" + name + "}", "1") |
| 98 | response = api_client.request(method, url, json={}) |
| 99 | assert response.status_code == 401, f"{method} {path} -> {response.status_code}" |
| 100 | checked += 1 |
| 101 | assert checked >= 30 # the whole statement + admin surface, not a sample |
| 102 | |
| 103 | |
| 104 | def test_reads_require_login_too(anon_client): |
| 105 | assert anon_client.get("/api/v1/audit").status_code == 401 |
| 106 | assert anon_client.get("/api/v1/audit/verify").status_code == 401 |
| 107 | assert anon_client.get("/api/v1/schema/entities").status_code == 401 |
| 108 | |
| 109 | |
| 110 | def test_no_request_model_still_accepts_an_actor_field(): |
| 111 | """Identity must not be expressible in any request body.""" |
| 112 | from aram_backend import admin_api, statement_api |
| 113 | |
| 114 | for module in (admin_api, statement_api): |
| 115 | for name in dir(module): |
| 116 | obj = getattr(module, name) |
| 117 | if isinstance(obj, type) and issubclass(obj, BaseModel): |
| 118 | assert "actor" not in obj.model_fields, ( |
| 119 | f"{module.__name__}.{name} still has an actor field" |
| 120 | ) |
| 121 | |
| 122 | |
| 123 | # ------------------------------------------------------------- token storage |
| 124 | def test_login_returns_a_256_bit_token_and_stores_only_its_hash(api_client): |
| 125 | r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"}) |
| 126 | token = r.json()["token"] |
| 127 | assert len(token) >= 43 # 32 random bytes, base64url |
| 128 | db, generator = _db(api_client) |
| 129 | try: |
| 130 | rows = db.query(AuthSession).all() |
| 131 | assert rows |
| 132 | assert all(row.token_hash == token_hash(token) or len(row.token_hash) == 64 for row in rows) |
| 133 | assert token not in {row.token_hash for row in rows} |
| 134 | assert db.query(AuthSession).filter_by(token_hash=token_hash(token)).one() |
| 135 | finally: |
| 136 | generator.close() |
| 137 | |
| 138 | |
| 139 | def test_two_logins_issue_different_tokens(api_client): |
| 140 | a = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"}) |
| 141 | b = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"}) |
| 142 | assert a.json()["token"] != b.json()["token"] |
| 143 | |
| 144 | |
| 145 | def test_expired_session_is_refused(api_client): |
| 146 | token = api_client.post( |
| 147 | "/api/v1/auth/login", json={"username": "root", "password": "supersecret"} |
| 148 | ).json()["token"] |
| 149 | db, generator = _db(api_client) |
| 150 | try: |
| 151 | row = db.query(AuthSession).filter_by(token_hash=token_hash(token)).one() |
| 152 | row.expires_at = datetime.now(UTC) - timedelta(seconds=1) |
| 153 | db.commit() |
| 154 | finally: |
| 155 | generator.close() |
| 156 | r = api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}) |
| 157 | assert r.status_code == 401 |
| 158 | |
| 159 | |
| 160 | def test_logout_revokes_the_session(api_client): |
| 161 | token = login(api_client, "root", "supersecret") |
| 162 | assert api_client.get("/api/v1/auth/me").status_code == 200 |
| 163 | assert api_client.post("/api/v1/auth/logout").status_code == 200 |
| 164 | r = api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}) |
| 165 | assert r.status_code == 401 |
| 166 | |
| 167 | |
| 168 | def test_deactivating_a_user_kills_their_sessions(api_client): |
| 169 | token = make_user(api_client, "prep", "preparer") |
| 170 | assert api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}).status_code == 200 |
| 171 | api_client.post("/api/v1/users/prep/active", json={"active": False}) |
| 172 | assert api_client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {token}"}).status_code == 401 |
| 173 | |
| 174 | |
| 175 | def test_garbage_and_missing_tokens_are_401(api_client): |
| 176 | assert api_client.get("/api/v1/auth/me", headers={"Authorization": "Bearer nope"}).status_code == 401 |
| 177 | assert api_client.get("/api/v1/auth/me", headers={"Authorization": "Basic abc"}).status_code == 401 |
| 178 | api_client.headers.pop("Authorization", None) |
| 179 | assert api_client.get("/api/v1/auth/me").status_code == 401 |
| 180 | |
| 181 | |
| 182 | # ------------------------------------------------------------------- lockout |
| 183 | def test_repeated_failures_lock_the_account(api_client): |
| 184 | for _ in range(MAX_FAILED_LOGINS): |
| 185 | r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "wrong"}) |
| 186 | assert r.status_code == 401 |
| 187 | # Even the CORRECT password is refused while the account is locked. |
| 188 | r = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "supersecret"}) |
| 189 | assert r.status_code == 401 |
| 190 | assert "قفل" in r.json()["detail"] |
| 191 | |
| 192 | |
| 193 | def test_lock_expires_and_the_counter_resets(api_client): |
| 194 | for _ in range(MAX_FAILED_LOGINS): |
| 195 | api_client.post("/api/v1/auth/login", json={"username": "root", "password": "wrong"}) |
| 196 | db, generator = _db(api_client) |
| 197 | try: |
| 198 | user = db.query(User).filter_by(username="root").one() |
| 199 | assert user.locked_until is not None |
| 200 | user.locked_until = datetime.now(UTC) - timedelta(seconds=1) |
| 201 | db.commit() |
| 202 | finally: |
| 203 | generator.close() |
| 204 | assert login(api_client, "root", "supersecret") |
| 205 | db, generator = _db(api_client) |
| 206 | try: |
| 207 | user = db.query(User).filter_by(username="root").one() |
| 208 | assert user.failed_login_count == 0 |
| 209 | assert user.locked_until is None |
| 210 | finally: |
| 211 | generator.close() |
| 212 | |
| 213 | |
| 214 | def test_unknown_username_does_not_reveal_itself(api_client): |
| 215 | known = api_client.post("/api/v1/auth/login", json={"username": "root", "password": "wrong"}) |
| 216 | unknown = api_client.post("/api/v1/auth/login", json={"username": "ghost", "password": "wrong"}) |
| 217 | assert known.status_code == unknown.status_code == 401 |
| 218 | assert known.json()["detail"] == unknown.json()["detail"] |
| 219 | |
| 220 | |
| 221 | # ------------------------------------------------------------- password work |
| 222 | def test_pbkdf2_work_factor_is_at_least_600k(session): |
| 223 | assert PBKDF2_ROUNDS >= 600_000 |
| 224 | user = create_user(session, username="alice", password="supersecret") |
| 225 | session.commit() |
| 226 | assert user.password_rounds >= 600_000 |
| 227 | assert user.password_hash == hash_password("supersecret", user.salt, PBKDF2_ROUNDS) |
| 228 | assert user.password_hash != "supersecret" |
| 229 | |
| 230 | |
| 231 | def test_legacy_200k_hash_is_upgraded_on_first_login(session): |
| 232 | """Pre-R1 accounts keep working and are silently rehashed to 600k.""" |
| 233 | user = create_user(session, username="legacy", password="supersecret") |
| 234 | user.password_rounds = 200_000 |
| 235 | user.password_hash = hash_password("supersecret", user.salt, 200_000) |
| 236 | session.commit() |
| 237 | assert authenticate(session, username="legacy", password="supersecret").username == "legacy" |
| 238 | assert user.password_rounds == PBKDF2_ROUNDS |
| 239 | assert user.password_hash == hash_password("supersecret", user.salt, PBKDF2_ROUNDS) |
| 240 | |
| 241 | |
| 242 | def test_short_password_still_refused(session): |
| 243 | with pytest.raises(UserError): |
| 244 | create_user(session, username="dave", password="short") |
| 245 | |
| 246 | |
| 247 | # --------------------------------------------------------- session lifecycle |
| 248 | def test_issue_and_resolve_round_trip(session): |
| 249 | user = create_user(session, username="alice", password="supersecret") |
| 250 | session.commit() |
| 251 | token = issue_session(session, user) |
| 252 | assert resolve_session(session, token).username == "alice" |
| 253 | with pytest.raises(AuthenticationError): |
| 254 | resolve_session(session, None) |
| 255 | with pytest.raises(AuthenticationError): |
| 256 | resolve_session(session, "not-a-token") |
| 257 | |
| 258 | |
| 259 | def test_inactive_user_cannot_resolve(session): |
| 260 | user = create_user(session, username="alice", password="supersecret") |
| 261 | session.commit() |
| 262 | token = issue_session(session, user) |
| 263 | set_active(session, username="alice", active=False) |
| 264 | session.commit() |
| 265 | with pytest.raises(AuthenticationError): |
| 266 | resolve_session(session, token) |
| 267 | |
| 268 | |
| 269 | # --------------------------------------------------------- audit attribution |
| 270 | def test_audit_actor_is_the_session_user_not_the_body(api_client): |
| 271 | make_user(api_client, "reviewer1", "reviewer") |
| 272 | login(api_client, "reviewer1", "supersecret") |
| 273 | year_id = api_client.post( |
| 274 | "/api/v1/companies", json={"code": "AU", "name": "شرکت", "year": 1404} |
| 275 | ).json()["year_id"] |
| 276 | api_client.post(f"/api/v1/years/{year_id}/approve", json={"actor": "root"}) |
| 277 | entries = api_client.get("/api/v1/audit").json()["entries"] |
| 278 | approve_entries = [e for e in entries if e["action"] == "approve"] |
| 279 | assert approve_entries |
| 280 | assert all(e["actor"] == "reviewer1" for e in approve_entries) |
| 281 | |
| 282 | |
| 283 | # ------------------------------------------------------------ backup confine |
| 284 | def test_backup_destination_outside_the_data_folder_is_refused(tmp_path): |
| 285 | store = tmp_path / "data" / "source_store" |
| 286 | store.mkdir(parents=True) |
| 287 | with pytest.raises(BackupError): |
| 288 | confine_dest("/etc/aram-backup", store_root=store) |
| 289 | with pytest.raises(BackupError): |
| 290 | confine_dest("../../escape", store_root=store) |
| 291 | with pytest.raises(BackupError): |
| 292 | confine_dest(tmp_path / "elsewhere" / "b", store_root=store) |
| 293 | |
| 294 | |
| 295 | def test_backup_destination_inside_the_data_folder_is_allowed(tmp_path): |
| 296 | store = tmp_path / "data" / "source_store" |
| 297 | store.mkdir(parents=True) |
| 298 | assert confine_dest("backup-1", store_root=store) == tmp_path / "data" / "backup-1" |
| 299 | |
| 300 | |
| 301 | def test_symlink_escape_is_refused(tmp_path): |
| 302 | store = tmp_path / "data" / "source_store" |
| 303 | store.mkdir(parents=True) |
| 304 | outside = tmp_path / "outside" |
| 305 | outside.mkdir() |
| 306 | link = tmp_path / "data" / "link" |
| 307 | link.symlink_to(outside, target_is_directory=True) |
| 308 | with pytest.raises(BackupError): |
| 309 | confine_dest("link/backup", store_root=store) |
| 310 | |
| 311 | |
| 312 | def test_backup_api_rejects_an_escaping_destination(api_client, tmp_path, monkeypatch): |
| 313 | from aram_backend.config import Settings |
| 314 | |
| 315 | monkeypatch.setattr( |
| 316 | "aram_backend.admin_api.get_settings", |
| 317 | lambda: Settings(source_store_root=str(tmp_path / "store")), |
| 318 | ) |
| 319 | (tmp_path / "store").mkdir(exist_ok=True) |
| 320 | r = api_client.post("/api/v1/backup", json={"dest": "/tmp/aram-escape"}) |
| 321 | assert r.status_code == 422 |
| 322 | assert "پوشهٔ داده" in r.json()["detail"] |
| 323 | |
| 324 | |
| 325 | def test_create_backup_service_confines_too(session, tmp_path): |
| 326 | store = tmp_path / "data" / "store" |
| 327 | store.mkdir(parents=True) |
| 328 | with pytest.raises(BackupError): |
| 329 | create_backup(session, tmp_path / "outside", store_root=store) |
| 330 | |
| 331 | |
| 332 | # ------------------------------------------------------- desktop launch token |
| 333 | @pytest.fixture |
| 334 | def desktop(tmp_path): |
| 335 | from aram_backend.database import reconfigure |
| 336 | |
| 337 | data_dir = tmp_path / "aram-data" |
| 338 | initialize_database(data_dir) |
| 339 | reconfigure(f"sqlite:///{data_dir / 'aram.db'}") |
| 340 | app = create_desktop_app() |
| 341 | with TestClient(app) as client: |
| 342 | yield client, app |
| 343 | |
| 344 | |
| 345 | def test_desktop_api_is_closed_without_the_launcher_grant(desktop): |
| 346 | client, _ = desktop |
| 347 | assert client.get("/api/v1/health").status_code == 200 # readiness stays open |
| 348 | assert client.post( |
| 349 | "/api/v1/users", json={"username": "evil", "password": "supersecret"} |
| 350 | ).status_code == 401 |
| 351 | assert client.post( |
| 352 | "/api/v1/auth/login", json={"username": "root", "password": "supersecret"} |
| 353 | ).status_code == 401 |
| 354 | |
| 355 | |
| 356 | def test_desktop_one_time_token_is_single_use(desktop): |
| 357 | client, app = desktop |
| 358 | token = app.state.launch_token |
| 359 | first = client.post("/api/v1/auth/launch", json={"token": token}) |
| 360 | assert first.status_code == 200 |
| 361 | grant = first.json()["grant"] |
| 362 | # Replaying the same launch token cannot mint a second grant. |
| 363 | assert client.post("/api/v1/auth/launch", json={"token": token}).status_code == 401 |
| 364 | client.headers.update({"X-Aram-Launch": grant}) |
| 365 | assert client.post( |
| 366 | "/api/v1/users", json={"username": "root", "password": "supersecret"} |
| 367 | ).status_code == 200 |
| 368 | |
| 369 | |
| 370 | def test_desktop_wrong_grant_is_refused(desktop): |
| 371 | client, app = desktop |
| 372 | client.post("/api/v1/auth/launch", json={"token": app.state.launch_token}) |
| 373 | client.headers.update({"X-Aram-Launch": "forged-grant"}) |
| 374 | assert client.post( |
| 375 | "/api/v1/users", json={"username": "evil", "password": "supersecret"} |
| 376 | ).status_code == 401 |
| 377 | |
| 378 | |
| 379 | def test_launch_guard_rejects_a_wrong_token(): |
| 380 | guard = LaunchGuard() |
| 381 | token = guard.arm() |
| 382 | with pytest.raises(AuthenticationError): |
| 383 | guard.exchange("wrong") |
| 384 | grant = guard.exchange(token) |
| 385 | guard.check(grant) |
| 386 | with pytest.raises(AuthenticationError): |
| 387 | guard.check("wrong") |
| 388 | with pytest.raises(AuthenticationError): |
| 389 | guard.exchange(token) |
| 390 | |
| 391 | |
| 392 | def test_launch_token_is_not_accepted_as_a_query_parameter(desktop): |
| 393 | """The token travels in the URL fragment, so it never reaches the server.""" |
| 394 | client, app = desktop |
| 395 | r = client.get(f"/api/v1/health?launch={app.state.launch_token}") |
| 396 | assert r.status_code == 200 |
| 397 | assert client.post( |
| 398 | "/api/v1/users", json={"username": "evil", "password": "supersecret"} |
| 399 | ).status_code == 401 |
| 400 | |
| 401 | |
| 402 | # ------------------------------------------------------------- misc surfaces |
| 403 | def test_sqlite_database_never_stores_a_plaintext_token(api_client, tmp_path): |
| 404 | token = login(api_client, "root", "supersecret") |
| 405 | db, generator = _db(api_client) |
| 406 | try: |
| 407 | url = db.get_bind().url |
| 408 | finally: |
| 409 | generator.close() |
| 410 | conn = sqlite3.connect(url.database) |
| 411 | try: |
| 412 | rows = conn.execute("SELECT token_hash FROM auth_sessions").fetchall() |
| 413 | finally: |
| 414 | conn.close() |
| 415 | assert rows |
| 416 | assert all(token not in row[0] for row in rows) |
| 417 | |
| 418 | |
| 419 | def test_role_change_takes_effect_on_the_next_request(api_client): |
| 420 | token = make_user(api_client, "prep", "preparer") |
| 421 | headers = {"Authorization": f"Bearer {token}"} |
| 422 | assert api_client.get("/api/v1/users", headers=headers).status_code == 403 |
| 423 | api_client.post("/api/v1/users/prep/role", json={"role": "admin"}) |
| 424 | assert api_client.get("/api/v1/users", headers=headers).status_code == 200 |
| 425 | |
| 426 | |
| 427 | def test_user_roles_are_unchanged(session): |
| 428 | assert {r.value for r in UserRole} == {"admin", "reviewer", "preparer"} |