Initial Homegate 0.4.0 with web UI, Compose and Gitea Actions
This commit is contained in:
182
tests/test_ui.py
Normal file
182
tests/test_ui.py
Normal file
@@ -0,0 +1,182 @@
|
||||
"""HTTP/session/config integration tests without external APIs or listening ports."""
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import yaml
|
||||
import homegate as h
|
||||
import homegate_ui as ui
|
||||
from test_ssh_and_zones import MemorySocket
|
||||
|
||||
BASE = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class PanelTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.config = self.root / 'config/services.yaml'
|
||||
self.config.parent.mkdir()
|
||||
self.config.write_bytes((BASE / 'config/services.yaml').read_bytes())
|
||||
self.control = self.root / 'control'
|
||||
self.password = self.root / 'password'
|
||||
self.password.write_text('local-test-password')
|
||||
self.panel = ui.Panel(self.config, self.control, 'http://192.168.0.10:8098',
|
||||
password_file=self.password)
|
||||
self.cookie = ''
|
||||
self.csrf = ''
|
||||
|
||||
def request(self, path='/api/state', body=None, peer='192.168.0.20', headers=None):
|
||||
method = 'GET' if body is None else 'POST'
|
||||
payload = b'' if body is None else json.dumps(body).encode()
|
||||
heads = {'Host': self.panel.authority, 'Cookie': self.cookie}
|
||||
if body is not None:
|
||||
heads.update({'Origin': self.panel.origin, 'Content-Type': 'application/json',
|
||||
'Content-Length': str(len(payload)), 'X-Homegate-CSRF': self.csrf})
|
||||
heads.update(headers or {})
|
||||
raw = f'{method} {path} HTTP/1.1\r\n' + ''.join(f'{k}: {v}\r\n' for k, v in heads.items()) + '\r\n'
|
||||
sock = MemorySocket(raw.encode() + payload)
|
||||
ui.handler_for(self.panel)(sock, (peer, 5000), None)
|
||||
header, data = sock.output.split(b'\r\n\r\n', 1)
|
||||
status = int(header.split()[1])
|
||||
response_headers = dict(line.decode().split(': ', 1) for line in header.split(b'\r\n')[1:])
|
||||
if 'application/json' in response_headers.get('Content-Type', ''):
|
||||
data = json.loads(data)
|
||||
return status, data, response_headers
|
||||
|
||||
def login(self):
|
||||
code, body, headers = self.request('/api/login', {'password': 'local-test-password'})
|
||||
self.assertEqual(code, 200)
|
||||
self.cookie = headers['Set-Cookie'].split(';')[0]
|
||||
self.csrf = body['csrf']
|
||||
return headers
|
||||
|
||||
def test_login_cookie_and_logout(self):
|
||||
self.assertEqual(self.request()[0], 401)
|
||||
headers = self.login()
|
||||
self.assertIn('HttpOnly; SameSite=Strict', headers['Set-Cookie'])
|
||||
self.assertEqual(self.request()[0], 200)
|
||||
self.assertEqual(self.request('/api/logout', {})[0], 200)
|
||||
self.assertEqual(self.request()[0], 401)
|
||||
|
||||
def test_wrong_password_rate_limited(self):
|
||||
for _ in range(5):
|
||||
self.assertEqual(self.request('/api/login', {'password': 'incorrect'})[0], 401)
|
||||
self.assertEqual(self.request('/api/login', {'password': 'incorrect'})[0], 429)
|
||||
|
||||
def test_origin_csrf_and_host_required(self):
|
||||
self.login()
|
||||
for headers in ({'Origin': 'https://attacker.example'}, {'X-Homegate-CSRF': ''}, {'Host': 'attacker.example'}):
|
||||
with self.subTest(headers=headers):
|
||||
self.assertEqual(self.request('/api/sync', {}, headers=headers)[0], 403)
|
||||
self.assertFalse((self.control / 'sync-request.json').exists())
|
||||
self.assertEqual(self.request('/api/sync', {})[0], 202)
|
||||
self.assertTrue((self.control / 'sync-request.json').exists())
|
||||
|
||||
def test_lan_acl_and_local_mode(self):
|
||||
for peer in ('8.8.8.8', '192.168.1.5'):
|
||||
self.assertEqual(self.request('/', peer=peer)[0], 403)
|
||||
self.assertEqual(self.request('/', peer='::ffff:192.168.0.20')[0], 200)
|
||||
self.panel = ui.Panel(self.config, self.control, 'http://127.0.0.1:8787', local=True)
|
||||
self.assertEqual(self.request('/api/session', peer='192.168.0.20')[0], 403)
|
||||
code, body, _ = self.request('/api/session', peer='127.0.0.1')
|
||||
self.assertEqual(code, 200)
|
||||
self.assertTrue(body['authenticated'])
|
||||
|
||||
def test_config_write_backups_and_conflicts(self):
|
||||
self.login()
|
||||
original = self.config.read_bytes()
|
||||
_, data, _ = self.request()
|
||||
new = copy.deepcopy(data['config'])
|
||||
new['domain_zones'].append('test.internal')
|
||||
code, saved, _ = self.request('/api/config', {'config': new, 'revision': data['revision']})
|
||||
self.assertEqual(code, 200)
|
||||
self.assertNotEqual(saved['revision'], data['revision'])
|
||||
self.assertIn('test.internal', h.load_config(self.config)['domain_zones'])
|
||||
backup = list((self.config.parent / 'backups').glob('*.yaml'))
|
||||
self.assertEqual(len(backup), 1)
|
||||
self.assertEqual(backup[0].read_bytes(), original)
|
||||
self.assertEqual(self.request('/api/config', {'config': new, 'revision': data['revision']})[0], 409)
|
||||
|
||||
def test_invalid_config_is_not_written(self):
|
||||
self.login()
|
||||
before = self.config.read_bytes()
|
||||
data = self.panel.status()
|
||||
data['config']['services'][0]['hostname'] = 'outside.example'
|
||||
code, _, _ = self.request('/api/config', {'config': data['config'], 'revision': data['revision']})
|
||||
self.assertEqual(code, 400)
|
||||
self.assertEqual(self.config.read_bytes(), before)
|
||||
|
||||
def test_malformed_json_and_missing_fields_return_400(self):
|
||||
self.login()
|
||||
for body in ([], None, 'string', {'revision': 'x'}):
|
||||
if body is not None:
|
||||
self.assertEqual(self.request('/api/config', body)[0], 400)
|
||||
|
||||
def test_downloads_require_login_and_no_private_files(self):
|
||||
for name in ('services.yaml', 'root-ca.crt', 'ssh-config'):
|
||||
self.assertEqual(self.request('/downloads/' + name)[0], 401)
|
||||
self.login()
|
||||
self.assertEqual(self.request('/downloads/root-ca.crt')[0], 404)
|
||||
self.assertIn(b'Host pve pve.home', self.request('/downloads/ssh-config')[1])
|
||||
for path in ('/downloads/../state/ca.json', '/state/ca.json', '/downloads/ui_password'):
|
||||
self.assertEqual(self.request(path)[0], 404)
|
||||
|
||||
def test_secure_cookie_expiry_and_static_csp(self):
|
||||
self.panel.origin = 'https://panel.home'
|
||||
self.panel.authority = 'panel.home'
|
||||
headers = self.login()
|
||||
self.assertIn('; Secure', headers['Set-Cookie'])
|
||||
self.assertIn("frame-ancestors 'none'", self.request('/')[2]['Content-Security-Policy'])
|
||||
with patch.object(ui.time, 'time', return_value=time.time() + 13 * 3600):
|
||||
self.assertEqual(self.request()[0], 401)
|
||||
|
||||
def test_freshness_reflects_controller_heartbeat(self):
|
||||
h.save_json(self.control / 'status.json', {'time': time.time()-200, 'max_age': 180, 'ok': True})
|
||||
self.assertFalse(self.panel.status()['controller']['fresh'])
|
||||
h.save_json(self.control / 'status.json', {'time': time.time(), 'max_age': 180, 'ok': False})
|
||||
self.assertTrue(self.panel.status()['controller']['fresh'])
|
||||
self.assertFalse(self.panel.status()['controller']['ok'])
|
||||
|
||||
def test_config_validation_does_not_mutate_ui_input(self):
|
||||
original, _ = self.panel.config_data()
|
||||
other = copy.deepcopy(original)
|
||||
h.validate_config(other)
|
||||
self.assertEqual(other, original)
|
||||
self.panel.save(other, self.panel.status()['revision'])
|
||||
self.assertNotIn('forward_host', yaml.safe_load(self.config.read_bytes())['services'][0])
|
||||
|
||||
def test_public_status_uses_applied_revision_without_keys(self):
|
||||
state = self.root / 'state'
|
||||
state.mkdir()
|
||||
config = h.load_config(self.config)
|
||||
ca = h.Authority(state, config['domain_zones'])
|
||||
ca.leaf('pve.home')
|
||||
applied = hashlib.sha256(self.config.read_bytes()).hexdigest()
|
||||
self.config.write_bytes(self.config.read_bytes() + b'\n# Edited while syncing\n')
|
||||
h.publish_panel_status(self.control, applied, config, state, ca, True, None)
|
||||
status = h.read_json(self.control / 'status.json')
|
||||
self.assertEqual(status['applied_revision'], applied)
|
||||
self.assertNotEqual(status['applied_revision'], self.panel.status()['revision'])
|
||||
self.assertIn('BEGIN CERTIFICATE', status['root']['pem'])
|
||||
self.assertEqual(status['certificates'][0]['hostname'], 'pve.home')
|
||||
self.assertNotIn('PRIVATE KEY', json.dumps(status))
|
||||
h.publish_panel_status(self.control, 'failed-revision', config, state, ca, False, 'API unavailable')
|
||||
self.assertEqual(h.read_json(self.control / 'status.json')['applied_revision'], applied)
|
||||
|
||||
def test_weak_password_or_invalid_origin_refused(self):
|
||||
self.password.write_text('short')
|
||||
with self.assertRaises(ui.UIError):
|
||||
ui.Panel(self.config, self.control, 'http://panel.home', password_file=self.password)
|
||||
with self.assertRaises(ui.UIError):
|
||||
ui.Panel(self.config, self.control, 'http://panel.home/path', local=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user