Add first-run web setup and Compose without environment or secrets
This commit is contained in:
158
tests/test_setup.py
Normal file
158
tests/test_setup.py
Normal file
@@ -0,0 +1,158 @@
|
||||
"""First-run UI, stored connections, live controller reload and process supervision."""
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import homegate as h
|
||||
import homegate_ui as ui
|
||||
import standalone
|
||||
from test_ssh_and_zones import MemorySocket
|
||||
|
||||
|
||||
class SetupTests(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.connections = self.config.with_name('connections.json')
|
||||
self.control = self.root / 'control'
|
||||
self.panel = ui.Panel(self.config, self.control, '', auth_required=False, connections_file=self.connections)
|
||||
self.cookie = ''
|
||||
self.csrf = ''
|
||||
self.settings = {'config': {'proxy_ip': '192.168.0.11', 'allowed_networks': ['192.168.0.0/24'],
|
||||
'domain_zones': ['home', 'home.arpa'], 'dns_mode': 'pihole6', 'interval_seconds': 60,
|
||||
'services': [], 'ssh_hosts': []}, 'connections': {'npm_url': 'http://192.168.0.11:81',
|
||||
'npm_identity': 'admin@example.com', 'npm_password': 'test-npm-secret',
|
||||
'pihole_url': 'http://192.168.0.2', 'pihole_password': 'test-pihole-secret'}, 'revision': ''}
|
||||
|
||||
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': '192.168.0.10:8098', 'Cookie': self.cookie}
|
||||
if body is not None:
|
||||
heads.update({'Origin': 'http://192.168.0.10:8098', '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)
|
||||
head, data = sock.output.split(b'\r\n\r\n', 1)
|
||||
response_headers = dict(line.decode().split(': ', 1) for line in head.split(b'\r\n')[1:])
|
||||
if 'application/json' in response_headers.get('Content-Type', ''):
|
||||
data = json.loads(data)
|
||||
return int(head.split()[1]), data, response_headers
|
||||
|
||||
def connect(self):
|
||||
code, body, headers = self.request('/api/session')
|
||||
self.assertEqual(code, 200)
|
||||
self.assertTrue(body['authenticated'])
|
||||
self.cookie = headers['Set-Cookie'].split(';')[0]
|
||||
self.csrf = body['csrf']
|
||||
|
||||
def install(self):
|
||||
self.connect()
|
||||
code, state, _ = self.request('/api/settings', self.settings)
|
||||
self.assertEqual(code, 200, state)
|
||||
self.assertFalse(state['setup_required'])
|
||||
return state
|
||||
|
||||
def test_blank_volume_opens_setup_without_password_or_env(self):
|
||||
self.connect()
|
||||
code, state, _ = self.request()
|
||||
self.assertEqual(code, 200)
|
||||
self.assertTrue(state['setup_required'])
|
||||
self.assertFalse(state['auth_required'])
|
||||
self.assertEqual(state['config']['services'], [])
|
||||
self.assertEqual(self.request('/healthz')[0], 200)
|
||||
self.assertEqual(self.request('/settings.js')[0], 200)
|
||||
self.assertFalse(self.config.exists())
|
||||
|
||||
def test_setup_persists_and_keeps_secrets_out_of_state_and_exports(self):
|
||||
state = self.install()
|
||||
stored = h.read_json(self.connections)
|
||||
self.assertEqual(stored['npm_password'], 'test-npm-secret')
|
||||
self.assertEqual(self.connections.stat().st_mode & 0o777, 0o600)
|
||||
self.assertTrue(state['connections']['npm_password_set'])
|
||||
self.assertNotIn('test-npm-secret', json.dumps(state))
|
||||
self.assertNotIn(b'test-npm-secret', self.request('/downloads/services.yaml')[1])
|
||||
self.assertTrue((self.control / 'sync-request.json').exists())
|
||||
restarted = ui.Panel(self.config, self.control, '', auth_required=False, connections_file=self.connections)
|
||||
self.assertFalse(restarted.status()['setup_required'])
|
||||
self.assertEqual(restarted.status()['connections']['npm_url'], stored['npm_url'])
|
||||
|
||||
def test_save_again_preserves_blank_passwords_and_changes_api_url(self):
|
||||
state = self.install()
|
||||
settings = copy.deepcopy(self.settings)
|
||||
settings['revision'] = state['revision']
|
||||
settings['connections']['npm_url'] = 'http://192.168.0.12:81'
|
||||
settings['connections']['npm_password'] = ''
|
||||
code, _, _ = self.request('/api/settings', settings)
|
||||
self.assertEqual(code, 200)
|
||||
stored = h.read_json(self.connections)
|
||||
self.assertEqual(stored['npm_password'], 'test-npm-secret')
|
||||
self.assertEqual(stored['npm_url'], 'http://192.168.0.12:81')
|
||||
|
||||
def test_invalid_settings_and_stale_revision_do_not_change_credentials(self):
|
||||
state = self.install()
|
||||
before = self.connections.read_bytes()
|
||||
for field, value in [('npm_url', 'http://192.168.0.12/api'), ('api_ca_pem', 'not a certificate')]:
|
||||
settings = copy.deepcopy(self.settings)
|
||||
settings['revision'] = state['revision']
|
||||
settings['connections'][field] = value
|
||||
self.assertEqual(self.request('/api/settings', settings)[0], 400)
|
||||
self.assertEqual(self.connections.read_bytes(), before)
|
||||
self.assertEqual(self.request('/api/settings', self.settings)[0], 409)
|
||||
self.assertEqual(self.connections.read_bytes(), before)
|
||||
|
||||
def test_acl_host_and_same_origin_work_without_fixed_origin(self):
|
||||
self.connect()
|
||||
self.assertEqual(self.request(peer='8.8.8.8')[0], 403)
|
||||
for headers in ({'Host': 'attacker.example'}, {'Origin': 'http://attacker.example'}, {'X-Homegate-CSRF': ''}):
|
||||
self.assertEqual(self.request('/api/settings', self.settings, headers=headers)[0], 403)
|
||||
self.install()
|
||||
self.assertEqual(self.request(peer='192.168.1.20')[0], 403)
|
||||
self.assertEqual(self.request(headers={'Host': 'homegate.home'})[0], 200)
|
||||
|
||||
def test_controller_reloads_connections_on_each_cycle(self):
|
||||
self.install()
|
||||
with patch.dict(os.environ, {'HOMEGATE_CONNECTIONS': str(self.connections)}, clear=True), patch.object(h, 'NPM') as npm, patch.object(h, 'PiHole') as dns, patch.object(h, 'reconcile'):
|
||||
h.cycle(self.settings['config'], self.root, None, {})
|
||||
npm.assert_called_with('http://192.168.0.11:81', 'NPM', True)
|
||||
npm.return_value.login.assert_called_with('admin@example.com', 'test-npm-secret')
|
||||
dns.return_value.login.assert_called_with('test-pihole-secret')
|
||||
settings = h.read_json(self.connections)
|
||||
settings.update(npm_url='http://192.168.0.12:81', npm_password='changed')
|
||||
h.save_json(self.connections, settings)
|
||||
h.cycle(self.settings['config'], self.root, None, {})
|
||||
npm.assert_called_with('http://192.168.0.12:81', 'NPM', True)
|
||||
npm.return_value.login.assert_called_with('admin@example.com', 'changed')
|
||||
|
||||
|
||||
class StandaloneTests(unittest.TestCase):
|
||||
def test_no_user_environment_required(self):
|
||||
env = standalone.runtime_environment({})
|
||||
self.assertEqual(env['UI_AUTH_MODE'], 'none')
|
||||
self.assertEqual(env['HOMEGATE_MANAGED_UI'], '1')
|
||||
self.assertNotIn('HOMEGATE_LAN_IP', env)
|
||||
self.assertNotIn('NPM_PASSWORD', env)
|
||||
|
||||
def test_child_failure_stops_remaining_processes(self):
|
||||
processes = []
|
||||
popen = subprocess.Popen
|
||||
def start(*args, **kwargs):
|
||||
process = popen(*args, **kwargs)
|
||||
processes.append(process)
|
||||
return process
|
||||
with patch.object(standalone.subprocess, 'Popen', side_effect=start):
|
||||
result = standalone.supervise([[sys.executable, '-c', 'raise SystemExit(3)'],
|
||||
[sys.executable, '-c', 'import time; time.sleep(60)']], {})
|
||||
self.assertEqual(result, 1)
|
||||
self.assertTrue(all(process.poll() is not None for process in processes))
|
||||
Reference in New Issue
Block a user