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>
This commit is contained in:
2026-04-27 11:30:21 -04:00
parent 0c12e3fc97
commit a43f9fbf0d
47 changed files with 4578 additions and 579 deletions
+353 -1
View File
@@ -1 +1,353 @@
# ... moved and adapted code from test_phase1_endpoints.py ...
#!/usr/bin/env python3
"""
Unit tests for network/DNS/DHCP Flask endpoints in api/app.py.
Covers:
GET /api/dns/records
POST /api/dns/records
DELETE /api/dns/records
GET /api/dns/status
GET /api/dhcp/leases
POST /api/dhcp/reservations
DELETE /api/dhcp/reservations
GET /api/network/info
POST /api/network/test
"""
import sys
import json
import unittest
from pathlib import Path
from unittest.mock import patch, MagicMock
api_dir = Path(__file__).parent.parent / 'api'
sys.path.insert(0, str(api_dir))
from app import app
class TestGetDnsRecords(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_get_dns_records_returns_200_with_list(self, mock_nm):
mock_nm.get_dns_records.return_value = [
{'name': 'myhost.cell', 'type': 'A', 'value': '192.168.1.10'},
{'name': 'nas.cell', 'type': 'A', 'value': '192.168.1.20'},
]
r = self.client.get('/api/dns/records')
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIsInstance(data, list)
self.assertEqual(len(data), 2)
@patch('app.network_manager')
def test_get_dns_records_returns_empty_list_when_none(self, mock_nm):
mock_nm.get_dns_records.return_value = []
r = self.client.get('/api/dns/records')
self.assertEqual(r.status_code, 200)
self.assertEqual(json.loads(r.data), [])
@patch('app.network_manager')
def test_get_dns_records_returns_500_on_exception(self, mock_nm):
mock_nm.get_dns_records.side_effect = Exception('CoreDNS unreachable')
r = self.client.get('/api/dns/records')
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestAddDnsRecord(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_add_dns_record_returns_200_on_valid_body(self, mock_nm):
mock_nm.add_dns_record.return_value = {'success': True}
r = self.client.post(
'/api/dns/records',
data=json.dumps({'name': 'printer.cell', 'type': 'A', 'value': '192.168.1.50'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIn('success', data)
@patch('app.network_manager')
def test_add_dns_record_returns_400_when_no_body(self, mock_nm):
r = self.client.post('/api/dns/records')
self.assertEqual(r.status_code, 400)
self.assertIn('error', json.loads(r.data))
mock_nm.add_dns_record.assert_not_called()
@patch('app.network_manager')
def test_add_dns_record_returns_500_on_exception(self, mock_nm):
mock_nm.add_dns_record.side_effect = Exception('Corefile write failed')
r = self.client.post(
'/api/dns/records',
data=json.dumps({'name': 'bad.cell', 'type': 'A', 'value': '10.0.0.1'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestDeleteDnsRecord(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_delete_dns_record_returns_200_on_success(self, mock_nm):
mock_nm.remove_dns_record.return_value = {'success': True}
r = self.client.delete(
'/api/dns/records',
data=json.dumps({'name': 'printer.cell'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 200)
@patch('app.network_manager')
def test_delete_dns_record_returns_500_on_exception(self, mock_nm):
mock_nm.remove_dns_record.side_effect = Exception('record not found')
r = self.client.delete(
'/api/dns/records',
data=json.dumps({'name': 'missing.cell'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestGetDnsStatus(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_get_dns_status_returns_200_with_status_dict(self, mock_nm):
mock_nm.get_dns_status.return_value = {
'running': True,
'records_count': 5,
'upstreams': ['1.1.1.1', '8.8.8.8'],
}
r = self.client.get('/api/dns/status')
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIn('running', data)
@patch('app.network_manager')
def test_get_dns_status_returns_500_on_exception(self, mock_nm):
mock_nm.get_dns_status.side_effect = Exception('CoreDNS not running')
r = self.client.get('/api/dns/status')
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestGetDhcpLeases(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_get_dhcp_leases_returns_200_with_list(self, mock_nm):
mock_nm.get_dhcp_leases.return_value = [
{'mac': 'aa:bb:cc:dd:ee:ff', 'ip': '192.168.1.101', 'hostname': 'laptop'},
]
r = self.client.get('/api/dhcp/leases')
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIsInstance(data, list)
self.assertEqual(len(data), 1)
self.assertEqual(data[0]['hostname'], 'laptop')
@patch('app.network_manager')
def test_get_dhcp_leases_returns_empty_list_when_no_leases(self, mock_nm):
mock_nm.get_dhcp_leases.return_value = []
r = self.client.get('/api/dhcp/leases')
self.assertEqual(r.status_code, 200)
self.assertEqual(json.loads(r.data), [])
@patch('app.network_manager')
def test_get_dhcp_leases_returns_500_on_exception(self, mock_nm):
mock_nm.get_dhcp_leases.side_effect = Exception('dnsmasq not running')
r = self.client.get('/api/dhcp/leases')
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestAddDhcpReservation(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_add_reservation_returns_200_on_valid_body(self, mock_nm):
mock_nm.add_dhcp_reservation.return_value = True
r = self.client.post(
'/api/dhcp/reservations',
data=json.dumps({'mac': 'aa:bb:cc:dd:ee:ff', 'ip': '192.168.1.50', 'hostname': 'printer'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIn('success', data)
@patch('app.network_manager')
def test_add_reservation_returns_400_when_no_body(self, mock_nm):
r = self.client.post('/api/dhcp/reservations')
self.assertEqual(r.status_code, 400)
self.assertIn('error', json.loads(r.data))
mock_nm.add_dhcp_reservation.assert_not_called()
@patch('app.network_manager')
def test_add_reservation_returns_400_when_mac_missing(self, mock_nm):
r = self.client.post(
'/api/dhcp/reservations',
data=json.dumps({'ip': '192.168.1.50'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 400)
self.assertIn('error', json.loads(r.data))
@patch('app.network_manager')
def test_add_reservation_returns_400_when_ip_missing(self, mock_nm):
r = self.client.post(
'/api/dhcp/reservations',
data=json.dumps({'mac': 'aa:bb:cc:dd:ee:ff'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 400)
self.assertIn('error', json.loads(r.data))
@patch('app.network_manager')
def test_add_reservation_uses_empty_hostname_when_omitted(self, mock_nm):
mock_nm.add_dhcp_reservation.return_value = True
self.client.post(
'/api/dhcp/reservations',
data=json.dumps({'mac': 'aa:bb:cc:dd:ee:ff', 'ip': '192.168.1.50'}),
content_type='application/json',
)
mock_nm.add_dhcp_reservation.assert_called_once_with('aa:bb:cc:dd:ee:ff', '192.168.1.50', '')
@patch('app.network_manager')
def test_add_reservation_returns_500_on_exception(self, mock_nm):
mock_nm.add_dhcp_reservation.side_effect = Exception('dnsmasq config error')
r = self.client.post(
'/api/dhcp/reservations',
data=json.dumps({'mac': 'aa:bb:cc:dd:ee:ff', 'ip': '192.168.1.50'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestDeleteDhcpReservation(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_delete_reservation_returns_200_on_success(self, mock_nm):
mock_nm.remove_dhcp_reservation.return_value = True
r = self.client.delete(
'/api/dhcp/reservations',
data=json.dumps({'mac': 'aa:bb:cc:dd:ee:ff'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIn('success', data)
@patch('app.network_manager')
def test_delete_reservation_returns_400_when_mac_missing(self, mock_nm):
r = self.client.delete(
'/api/dhcp/reservations',
data=json.dumps({'hostname': 'printer'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 400)
self.assertIn('error', json.loads(r.data))
mock_nm.remove_dhcp_reservation.assert_not_called()
@patch('app.network_manager')
def test_delete_reservation_returns_400_when_no_body(self, mock_nm):
r = self.client.delete('/api/dhcp/reservations')
self.assertEqual(r.status_code, 400)
self.assertIn('error', json.loads(r.data))
@patch('app.network_manager')
def test_delete_reservation_returns_500_on_exception(self, mock_nm):
mock_nm.remove_dhcp_reservation.side_effect = Exception('reservation not found')
r = self.client.delete(
'/api/dhcp/reservations',
data=json.dumps({'mac': 'aa:bb:cc:dd:ee:ff'}),
content_type='application/json',
)
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestGetNetworkInfo(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_get_network_info_returns_200_with_info_dict(self, mock_nm):
mock_nm.get_network_info.return_value = {
'interfaces': ['eth0', 'wg0'],
'gateway': '192.168.1.1',
'dns': ['127.0.0.1'],
}
r = self.client.get('/api/network/info')
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIn('interfaces', data)
@patch('app.network_manager')
def test_get_network_info_returns_500_on_exception(self, mock_nm):
mock_nm.get_network_info.side_effect = Exception('network unreachable')
r = self.client.get('/api/network/info')
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
class TestNetworkTest(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.client = app.test_client()
@patch('app.network_manager')
def test_network_test_returns_200_with_result(self, mock_nm):
mock_nm.test_connectivity.return_value = {
'internet': True,
'dns': True,
'latency_ms': 15,
}
r = self.client.post('/api/network/test')
self.assertEqual(r.status_code, 200)
data = json.loads(r.data)
self.assertIn('internet', data)
@patch('app.network_manager')
def test_network_test_returns_500_on_exception(self, mock_nm):
mock_nm.test_connectivity.side_effect = Exception('ping failed')
r = self.client.post('/api/network/test')
self.assertEqual(r.status_code, 500)
self.assertIn('error', json.loads(r.data))
if __name__ == '__main__':
unittest.main()