#!/usr/bin/env python3 """ Tests for the before_request authentication / authorization hook in app.py. The hook is expected to: - Return 401 for unauthenticated requests to /api/* (except /api/auth/*) - Return 403 for peer-role sessions trying to access non-/api/peer/* routes - Allow admin sessions through to any /api/* route - Allow peer sessions through to /api/peer/* routes - Block admin sessions from /api/peer/* routes (peer-only zone) Fixtures are deliberately kept in this file so they remain self-contained, but they delegate to the same helpers as test_auth_routes.py. """ import os import sys import json from pathlib import Path from unittest.mock import patch import pytest sys.path.insert(0, str(Path(__file__).parent.parent / 'api')) from app import app from auth_manager import AuthManager # ── shared setup helpers ────────────────────────────────────────────────────── def _make_auth_manager(tmp_path): data_dir = str(tmp_path / 'data') config_dir = str(tmp_path / 'config') os.makedirs(data_dir, exist_ok=True) os.makedirs(config_dir, exist_ok=True) mgr = AuthManager(data_dir=data_dir, config_dir=config_dir) mgr.create_user('admin', 'AdminPass123!', 'admin') mgr.create_user('alice', 'AlicePass123!', 'peer') return mgr def _login(client, username, password): return client.post( '/api/auth/login', data=json.dumps({'username': username, 'password': password}), content_type='application/json', ) def _patched_client(auth_mgr): """Context manager: returns a test_client with auth_manager patched.""" import contextlib @contextlib.contextmanager def _cm(): app.config['TESTING'] = True app.config['SECRET_KEY'] = 'test-secret' with patch('app.auth_manager', auth_mgr): try: import auth_routes with patch.object(auth_routes, 'auth_manager', auth_mgr, create=True): with app.test_client() as c: yield c except (ImportError, AttributeError): with app.test_client() as c: yield c return _cm() # ── fixtures ────────────────────────────────────────────────────────────────── @pytest.fixture def auth_mgr(tmp_path): return _make_auth_manager(tmp_path) @pytest.fixture def anon_client(auth_mgr): with _patched_client(auth_mgr) as client: yield client @pytest.fixture def admin_client(auth_mgr): with _patched_client(auth_mgr) as client: r = _login(client, 'admin', 'AdminPass123!') assert r.status_code == 200, f'admin login failed: {r.status_code} {r.data}' yield client @pytest.fixture def peer_client(auth_mgr): with _patched_client(auth_mgr) as client: r = _login(client, 'alice', 'AlicePass123!') assert r.status_code == 200, f'alice login failed: {r.status_code} {r.data}' yield client # ── anonymous access ────────────────────────────────────────────────────────── def test_anon_blocked_from_api(anon_client): r = anon_client.get('/api/config') assert r.status_code == 401 def test_anon_blocked_from_api_status(anon_client): r = anon_client.get('/api/status') assert r.status_code == 401 def test_anon_allowed_health(anon_client): """Non-/api/ paths like /health must remain public.""" r = anon_client.get('/health') assert r.status_code != 401 def test_anon_allowed_auth_login(anon_client): """/api/auth/login itself must be reachable without a session.""" r = _login(anon_client, 'admin', 'AdminPass123!') # The route is reachable — 200 or 401 (wrong creds), but NOT 403/blocked assert r.status_code in (200, 401, 400) def test_anon_blocked_from_peer_routes(anon_client): r = anon_client.get('/api/peer/services') assert r.status_code == 401 def test_setup_routes_bypass_auth(anon_client): """/api/setup/* must be reachable without a session — setup runs before any account exists.""" r = anon_client.get('/api/setup/status') assert r.status_code != 401 def test_anon_blocked_from_peer_dashboard(anon_client): r = anon_client.get('/api/peer/dashboard') assert r.status_code == 401 # ── admin access ────────────────────────────────────────────────────────────── def test_admin_allowed_config(admin_client): r = admin_client.get('/api/config') assert r.status_code not in (401, 403) def test_admin_allowed_status(admin_client): r = admin_client.get('/api/status') assert r.status_code not in (401, 403) def test_admin_blocked_from_peer_only_routes(admin_client): """Peer-only routes (/api/peer/*) must not be accessible by admin sessions.""" r = admin_client.get('/api/peer/dashboard') assert r.status_code == 403 def test_admin_blocked_from_peer_services(admin_client): r = admin_client.get('/api/peer/services') assert r.status_code == 403 # ── peer access ─────────────────────────────────────────────────────────────── def test_peer_blocked_from_admin_routes(peer_client): r = peer_client.get('/api/config') assert r.status_code == 403 def test_peer_blocked_from_wireguard_settings(peer_client): r = peer_client.get('/api/wireguard/status') assert r.status_code == 403 def test_peer_blocked_from_network_settings(peer_client): r = peer_client.get('/api/network/config') assert r.status_code == 403 def test_peer_allowed_peer_dashboard(peer_client): r = peer_client.get('/api/peer/dashboard') # Not 403 — either 200, 404 (not yet implemented), or 500 (backend error) assert r.status_code != 403 def test_peer_allowed_peer_services(peer_client): r = peer_client.get('/api/peer/services') assert r.status_code != 403 # ── auth endpoints exempt from session requirement ──────────────────────────── def test_anon_auth_login_not_blocked_by_hook(anon_client): """The before_request hook must whitelist /api/auth/* so login is accessible.""" r = anon_client.post( '/api/auth/login', data=json.dumps({'username': 'doesnotmatter', 'password': 'x'}), content_type='application/json', ) # Hook must not return 401 for /api/auth/login; the route itself may return 401 # for bad credentials but that is a different 401 (from the route, not the hook). # The key contract: we must NOT get a 403 "Forbidden" from the hook. assert r.status_code != 403 def test_anon_can_reach_auth_namespace(anon_client): """GET /api/auth/me returns 401 from the route (unauthenticated) not from hook.""" r = anon_client.get('/api/auth/me') # 401 is expected here but it must originate from the route, not a redirect/block # on a non-auth path. The response should be JSON, not a redirect (3xx). assert r.status_code not in (301, 302, 403) def test_anon_can_reach_peer_sync_endpoint(anon_client): """POST /api/cells/peer-sync/* must not be blocked by session auth. The peer-sync endpoint authenticates via source IP + WireGuard pubkey. It must not return 401/403 from the global enforce_auth hook — the route handler itself produces any rejection. """ r = anon_client.post( '/api/cells/peer-sync/permissions', json={}, content_type='application/json', ) # 400 (bad payload) or 403 (IP/pubkey rejected) are acceptable — 401 from # the global auth hook is NOT acceptable because the route has its own guard. assert r.status_code != 401