112 lines
5.2 KiB
Python
112 lines
5.2 KiB
Python
"""Run manually inside a disposable standalone container: python - write|verify < this file."""
|
|
import hashlib
|
|
import http.cookiejar
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
origin = 'http://127.0.0.1:8081'
|
|
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
|
urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
|
|
csrf = ''
|
|
def request(path, body=None):
|
|
headers = {}
|
|
if body is not None:
|
|
headers = {'Origin': origin, 'Content-Type': 'application/json', 'X-Homegate-CSRF': csrf}
|
|
payload = json.dumps(body).encode() if body is not None else None
|
|
with opener.open(urllib.request.Request(origin + path, payload, headers), timeout=3) as response:
|
|
data = response.read()
|
|
return json.loads(data) if 'application/json' in response.headers.get('Content-Type', '') else data
|
|
|
|
def wait_for(predicate):
|
|
deadline = time.monotonic() + 20
|
|
while time.monotonic() < deadline:
|
|
value = predicate()
|
|
if value:
|
|
return value
|
|
time.sleep(0.25)
|
|
raise AssertionError('Timed out waiting for controller')
|
|
|
|
def session_ready():
|
|
try:
|
|
return request('/api/session')
|
|
except urllib.error.HTTPError:
|
|
raise
|
|
except urllib.error.URLError:
|
|
return None
|
|
|
|
session = wait_for(session_ready)
|
|
assert session['authenticated']
|
|
csrf = session['csrf']
|
|
state = request('/api/state')
|
|
assert not state['auth_required']
|
|
assert b'renderManagedSettings' in request('/settings.js')
|
|
|
|
if sys.argv[-1] == 'write':
|
|
assert state['setup_required']
|
|
seen = []
|
|
class API(BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
length = int(self.headers.get('Content-Length', '0'))
|
|
body = json.loads(self.rfile.read(length)) if length else None
|
|
if self.path == '/api/tokens':
|
|
seen.append((self.server.server_port, body['identity'], body['secret']))
|
|
value = {'token': 'disposable-token'}
|
|
elif self.path == '/api/auth':
|
|
value = {'session': {'valid': True, 'sid': 'disposable-sid', 'csrf': 'disposable-csrf'}}
|
|
elif self.path == '/api/config/dns':
|
|
value = {'config': {'dns': {'hosts': [], 'cnameRecords': []}}}
|
|
else:
|
|
value = []
|
|
data = json.dumps(value).encode()
|
|
self.send_response(200)
|
|
self.send_header('Content-Type', 'application/json')
|
|
self.send_header('Content-Length', str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
do_POST = do_GET
|
|
do_DELETE = do_GET
|
|
def log_message(self, *args):
|
|
pass
|
|
servers = [ThreadingHTTPServer(('127.0.0.1', port), API) for port in (18181, 18182)]
|
|
for server in servers:
|
|
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
try:
|
|
config = state['config']
|
|
config.update(proxy_ip='192.168.42.11', allowed_networks=['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'],
|
|
ssh_hosts=[{'aliases': ['qa-nas'], 'host': '192.168.42.50', 'port': 22, 'user': 'test'}])
|
|
links = {'npm_url': 'http://127.0.0.1:18181', 'npm_identity': 'test@example.invalid',
|
|
'npm_password': 'disposable-npm-password', 'pihole_url': 'http://127.0.0.1:18181',
|
|
'pihole_password': 'disposable-pihole-password'}
|
|
state = request('/api/settings', {'config': config, 'connections': links, 'revision': state['revision']})
|
|
assert not state['setup_required']
|
|
wait_for(lambda: request('/api/state')['controller'].get('ok'))
|
|
assert (18181, 'test@example.invalid', 'disposable-npm-password') in seen
|
|
ca_before = Path('/data/root-ca.crt').read_bytes()
|
|
links.update(npm_url='http://127.0.0.1:18182', npm_password='changed-npm-password')
|
|
request('/api/settings', {'config': config, 'connections': links, 'revision': state['revision']})
|
|
wait_for(lambda: (18182, 'test@example.invalid', 'changed-npm-password') in seen)
|
|
assert Path('/data/root-ca.crt').read_bytes() == ca_before
|
|
assert 'changed-npm-password' not in json.dumps(request('/api/state'))
|
|
with opener.open('http://127.0.0.1:8080/healthz') as response:
|
|
assert response.status == 200
|
|
assert b'Host qa-nas' in request('/downloads/ssh-config')
|
|
Path('/data/.qa-fingerprint').write_text(hashlib.sha256(ca_before).hexdigest())
|
|
print('Standalone: no-env onboarding, real HTTP settings, NPM/Pi-hole mock login, live API reload, CA and SSH verified.')
|
|
finally:
|
|
for server in servers:
|
|
server.shutdown()
|
|
else:
|
|
assert not state['setup_required']
|
|
assert state['connections']['npm_url'] == 'http://127.0.0.1:18182'
|
|
assert state['connections']['npm_password_set']
|
|
assert state['config']['ssh_hosts'][0]['aliases'] == ['qa-nas']
|
|
assert hashlib.sha256(Path('/data/root-ca.crt').read_bytes()).hexdigest() == Path('/data/.qa-fingerprint').read_text()
|
|
assert b'Host qa-nas' in request('/downloads/ssh-config')
|
|
print('Standalone restart: setup, credentials, SSH inventory and CA retained; no login or environment required.')
|