Files
pic/tests/e2e/wg/conftest.py
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

121 lines
3.4 KiB
Python

import os
import shutil
import pytest
import tempfile
import secrets
from helpers.wg_runner import WGInterface, build_wg_config, cleanup_stale_e2e_interfaces
def pytest_configure(config):
if not shutil.which('wg-quick'):
pytest.skip('wg-quick not found — skipping WireGuard E2E tests', allow_module_level=True)
@pytest.fixture(scope='session', autouse=True)
def cleanup_stale_wg_interfaces():
cleanup_stale_e2e_interfaces()
yield
cleanup_stale_e2e_interfaces()
@pytest.fixture(scope='session')
def wg_server_info(admin_client, pic_host):
"""Get server public key and listen port from the running API."""
# Public key lives at /api/wireguard/keys
keys_r = admin_client.get('/api/wireguard/keys')
keys = keys_r.json()
server_pubkey = keys.get('public_key', '')
# Port comes from the WireGuard config or status
port = 51820
try:
status = admin_client.get('/api/wireguard/status').json()
port = (
status.get('listen_port') or
status.get('port') or
status.get('ListenPort') or
51820
)
except Exception:
pass
return {
'public_key': server_pubkey,
'endpoint': pic_host,
'port': int(port),
}
@pytest.fixture
def connected_peer(make_peer, wg_server_info, tmp_path):
"""
Creates a peer, builds its WireGuard config, brings the tunnel up, yields,
then tears everything down.
Requires: sudo wg-quick available on the test runner.
"""
peer = make_peer('e2etest-wg-basic', service_access=['calendar', 'files', 'mail', 'webdav'])
iface_name = f"pic-e2e-{secrets.token_hex(3)}"
conf_path = str(tmp_path / f"{iface_name}.conf")
config_text = build_wg_config(
private_key=peer['private_key'],
peer_ip=peer['ip'],
server_pubkey=wg_server_info['public_key'],
server_endpoint=wg_server_info['endpoint'],
server_port=wg_server_info['port'],
allowed_ips='10.0.0.0/24',
)
# Write config with restricted permissions
with open(conf_path, 'w') as f:
f.write(config_text)
os.chmod(conf_path, 0o600)
iface = WGInterface(conf_path, iface_name)
try:
iface.bring_up()
peer['iface'] = iface
peer['conf_path'] = conf_path
yield peer
finally:
iface.bring_down()
try:
os.unlink(conf_path)
except Exception:
pass
@pytest.fixture
def full_tunnel_peer(make_peer, wg_server_info, tmp_path):
"""Like connected_peer but with AllowedIPs=0.0.0.0/0 (full tunnel)."""
peer = make_peer('e2etest-wg-fulltunnel')
iface_name = f"pic-e2e-{secrets.token_hex(3)}"
conf_path = str(tmp_path / f"{iface_name}.conf")
config_text = build_wg_config(
private_key=peer['private_key'],
peer_ip=peer['ip'],
server_pubkey=wg_server_info['public_key'],
server_endpoint=wg_server_info['endpoint'],
server_port=wg_server_info['port'],
allowed_ips='0.0.0.0/0',
)
with open(conf_path, 'w') as f:
f.write(config_text)
os.chmod(conf_path, 0o600)
iface = WGInterface(conf_path, iface_name)
try:
iface.bring_up()
peer['iface'] = iface
peer['conf_path'] = conf_path
yield peer
finally:
iface.bring_down()
try:
os.unlink(conf_path)
except Exception:
pass