Files
pic/tests/test_enforce_auth_configured.py
T
roof a43f9fbf0d fix: full security audit remediation — P0/P1/P2/P3 fixes + 1020 passing tests
P0 — Broken functionality:
- Fix 12+ endpoints with wrong manager method signatures (email/calendar/file/routing)
- Fix email_manager.delete_email_user() missing domain arg
- Fix cell-link DNS forwarding wiped on every peer change (generate_corefile now
  accepts cell_links param; add/remove_cell_dns_forward no longer clobber the file)
- Fix Flask SECRET_KEY regenerating on every restart (persisted to DATA_DIR)
- Fix _next_peer_ip exhaustion returning 500 instead of 409
- Fix ConfigManager Caddyfile path (/app/config-caddy/)
- Fix UI double-add and wrong-key peer bugs in Peers.jsx / WireGuard.jsx
- Remove hardcoded credentials from Dashboard.jsx

P1 — Security:
- CSRF token validation on all POST/PUT/DELETE/PATCH to /api/* (double-submit pattern)
- enforce_auth: 503 only when users file readable but empty; never bypass on IOError
- WireGuard add_cell_peer: validate pubkey, name, endpoint against strict regexes
- DNS add_cell_dns_forward: validate IP and domain; reject injection chars
- DNS zone write: realpath containment + record content validation
- iptables comment /32 suffix prevents substring match deleting wrong peer rules
- is_local_request() trusts only loopback + 172.16.0.0/12 (Docker bridge)
- POST /api/containers: volume allow-list prevents arbitrary host mounts
- file_manager: bcrypt ($2b→$2y) for WebDAV; realpath containment in delete_user
- email/calendar: stop persisting plaintext passwords in user records
- routing_manager: validate IPs, networks, and interface names
- peer_registry: write peers.json at mode 0o600
- vault_manager: Fernet key file at mode 0o600
- CORS: lock down to explicit origin list
- domain/cell_name validation: reject newline, brace, semicolon injection chars

P2 — Architecture:
- Peer add: rollback registry entry if firewall rules fail post-add
- restart_service(): base class now calls _restart_container(); email and calendar
  managers call cell-mail / cell-radicale respectively
- email/calendar managers sync user list (no passwords) to cell_config.json
- Pending-restart flag cleared only after helper subprocess exits with code 0
- docker-compose.yml: add config-caddy volume to API container

P3 — Tests (854 → 1020):
- Fill test_email_endpoints.py, test_calendar_endpoints.py,
  test_network_endpoints.py, test_routing_endpoints.py
- New: test_peer_management_update.py, test_peer_management_edge_cases.py,
  test_input_validation.py, test_enforce_auth_configured.py,
  test_cell_link_dns.py, test_logs_endpoints.py, test_cells_endpoints.py,
  test_is_local_request_per_endpoint.py, test_caddy_routing.py
- E2E conftest: skip WireGuard suite when wg-quick absent
- Update existing tests to match fixed signatures and comment formats

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 11:30:21 -04:00

143 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""
Tests for the enforce_auth before_request hook in api/app.py.
The hook has two distinct behaviours depending on the auth store state:
- users file exists and is POPULATED → auth is enforced (unauthenticated → 401)
- users file exists but is EMPTY → 503 (auth not configured)
- users file does not exist / unreadable → bypass (pre-auth compat mode)
These tests create real AuthManager instances pointing at tmp directories so
that list_users() and the file-readability check both behave exactly as they
do in production.
"""
import os
import sys
import json
import pytest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).parent.parent / 'api'))
@pytest.fixture
def flask_client():
from app import app
app.config['TESTING'] = True
return app.test_client()
@pytest.fixture
def populated_auth_manager(tmp_path):
"""AuthManager whose users file contains at least one admin account."""
from auth_manager import AuthManager
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)
# Create an admin so list_users() is non-empty
ok = mgr.create_user('admin', 'AdminPass123!', 'admin')
assert ok, 'Could not seed admin user for test'
return mgr
@pytest.fixture
def empty_auth_manager(tmp_path):
"""AuthManager whose users file exists and is readable but contains no users."""
from auth_manager import AuthManager
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)
# The constructor creates the file with '[]' (empty list). We do NOT add
# any user, so list_users() returns [] but the file is readable.
assert mgr.list_users() == [], 'Expected empty user list'
return mgr
# ── populated store → auth enforced ──────────────────────────────────────────
def test_populated_auth_manager_unauthenticated_request_gets_401(
flask_client, populated_auth_manager
):
"""When the auth store has users, unauthenticated API requests must get 401."""
with patch('app.auth_manager', populated_auth_manager):
r = flask_client.get('/api/status')
assert r.status_code == 401
data = json.loads(r.data)
assert 'error' in data
def test_populated_auth_manager_401_body_says_not_authenticated(
flask_client, populated_auth_manager
):
"""The 401 body must clearly indicate the session is missing."""
with patch('app.auth_manager', populated_auth_manager):
r = flask_client.get('/api/peers')
assert r.status_code == 401
data = json.loads(r.data)
assert 'Not authenticated' in data.get('error', '')
def test_populated_auth_manager_non_api_path_bypasses_auth(
flask_client, populated_auth_manager
):
"""Non-API paths like /health must always be public."""
with patch('app.auth_manager', populated_auth_manager):
r = flask_client.get('/health')
assert r.status_code == 200
def test_populated_auth_manager_auth_namespace_bypasses_auth(
flask_client, populated_auth_manager
):
"""The /api/auth/* namespace must always be accessible without a session."""
with patch('app.auth_manager', populated_auth_manager):
r = flask_client.get('/api/auth/me')
# /api/auth/me may return 401 from the route itself (no session), but it
# must NOT be blocked by enforce_auth; the enforce_auth hook must return None
# for /api/auth/* paths. The status must not be 503.
assert r.status_code != 503
# ── empty store → 503 ────────────────────────────────────────────────────────
def test_empty_auth_manager_returns_503_for_api_requests(
flask_client, empty_auth_manager
):
"""When the users file exists and is readable but empty, /api/* must get 503."""
with patch('app.auth_manager', empty_auth_manager):
r = flask_client.get('/api/status')
assert r.status_code == 503
data = json.loads(r.data)
assert 'error' in data
def test_empty_auth_manager_503_body_mentions_configuration(
flask_client, empty_auth_manager
):
"""The 503 error body must mention that auth is not configured."""
with patch('app.auth_manager', empty_auth_manager):
r = flask_client.get('/api/config')
assert r.status_code == 503
data = json.loads(r.data)
error_text = data.get('error', '')
assert 'not configured' in error_text.lower() or 'Authentication' in error_text
def test_empty_auth_manager_non_api_path_bypasses_503(
flask_client, empty_auth_manager
):
"""Even with an empty auth store, /health must remain accessible."""
with patch('app.auth_manager', empty_auth_manager):
r = flask_client.get('/health')
assert r.status_code == 200
if __name__ == '__main__':
pytest.main([__file__, '-v'])