Release v122 with Tachyon integration and resilient Xray downloads
OpenWrt IPK and APK / Validate source and resolve stable SDKs (push) Waiting to run

This commit is contained in:
kzolotarev95 committed 2026-11-21 22:53:52 +04:00
1 parent f4ccbf82f3
commit 70a4705e67
50 files changed
+3173 -181

No files matched your search

+12 -8
View File
@@ -1,33 +1,37 @@
# Версия v121
# Версия v122
Версия v121 указана в панели VPS, на экране входа, в мобильной шапке,
Выпуск использует main и отдельный тег v122. GitHub Actions собирает IPK/APK,
проверяет их и прикладывает к Releases → v122 после успешного завершения сборок
и установки/обновления/удаления в OpenWrt VM. Выпущенная v121 сохраняется.
Версия v122 указана в панели VPS, на экране входа, в мобильной шапке,
CGI и представлении LuCI роутера. Скрипты локальной установки, их проверки
и документация используют тот же номер. Ссылки источников не менялись.
Установить локальную сборку на VPS:
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v121.ps1" -Vps "root@179.43.187.107" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v122.ps1" -Vps "root@132.243.19.232" -Action Install
```
В ходе текущего тестирования обновления через кнопку вместо обычной установки
нужно использовать тестовые сборки из [HUB_UPDATE.md](HUB_UPDATE.md):
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\test-hub-self-update.ps1" -Vps "root@179.43.187.107" -Action Retest
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\test-hub-self-update.ps1" -Vps "root@132.243.19.232" -Action Retest
```
Установить версию интерфейса роутера (CGI и LuCI):
```powershell
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v121.ps1" -Router "root@192.168.2.1" -Action Install
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\Documents\openwrt overlay\vps\deploy-version-v122.ps1" -Router "root@192.168.2.1" -Action Install
```
Скрипт сохраняет первую резервную копию и проверяет файлы до установки.
На VPS дополнительно сверяется SHA-256 запущенной сборки через `/health?panel-update=1`;
ответ от другой сборки не подтверждает успешную установку.
Обновление через кнопку не позволяет установить более старую опубликованную
версию поверх локальной v121. Для исправлений с тем же номером версии
версию поверх локальной v122. Для исправлений с тем же номером версии
по-прежнему проверяется SHA-256. Отдельный баннер «последняя версия» скрыт:
при отсутствии обновлений остаётся зелёная кнопка «Обновление не требуется».
При ошибке после замены возвращает файлы предыдущей попытки.
@@ -37,8 +41,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Users\k.zolotarev95\
Для отката обычной установки VPS либо роутера повторить соответствующую
команду с `-Action Rollback`. Копии:
- VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-v121`.
- Роутер: `/root/owrt-remote-backup-before-v121` (CGI и LuCI).
- VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-v122`.
- Роутер: `/root/owrt-remote-backup-before-v122` (CGI и LuCI).
Для возврата из тестового режима обновления VPS повторить команду
`test-hub-self-update.ps1` с `-Action Restore`: его копия хранится отдельно,
+1 -1
View File
@@ -104,7 +104,7 @@ logger() { printf '%s\\n' "$3" | sh "$TEST_LOG_HELPER" append; }
self.assertIn('GLOBAL_LOGS_ROUTER_Install_OK', result.stdout)
for item in ('cgi', 'luci'):
installed = self.root / self.targets[item].lstrip('/')
self.assertIn('v121', installed.read_text(encoding='utf-8'))
self.assertIn('v122', installed.read_text(encoding='utf-8'))
for item, data in self.initial.items():
self.assertEqual(self.backup.joinpath(item).read_bytes(), data)
result = self.deploy('Rollback')
+15 -1
View File
@@ -33,6 +33,16 @@ def preview_pages():
for path, page in pages.items()}
def tachyon_layout_preview():
page = b'''<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<style>html,body{margin:0}.tachyon-bg-layer{position:fixed;inset:0;pointer-events:none}
.tachyon-bg-layer svg{width:100%;height:100%;display:block}
#maincontent{position:relative;padding:8px;box-sizing:border-box}main{height:400px}</style>
</head><body><div class="tachyon-bg-layer"><svg viewBox="0 0 1600 900"></svg></div>
<div id="maincontent"><main>Tachyon dashboard</main></div></body></html>'''
return {'synthetic': hub.inject_hub_appearance('/tachyon/node-10/', page, 'text/html').decode()}
class GlobalHubDesignTests(unittest.TestCase):
def test_generated_pages_receive_the_shared_head(self):
pages = {
@@ -54,10 +64,14 @@ class GlobalHubDesignTests(unittest.TestCase):
self.assertEqual(dashboard.count("owrt-hub-design-head"), 1)
luci = b"<html><head><title>LuCI</title></head><body>router</body></html>"
self.assertEqual(hub.inject_hub_appearance("/access/main/", luci, "text/html"), luci)
for path in ('/tachyon/node-10/', '/tachyon/node-10/cgi-bin/luci/?view=main'):
self.assertEqual(hub.inject_hub_appearance(path, luci, 'text/html; charset=utf-8'), luci)
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--export-preview":
if len(sys.argv) == 3 and sys.argv[1] == "--export-tachyon-layout":
pathlib.Path(sys.argv[2]).write_text(json.dumps(tachyon_layout_preview()), encoding='utf-8')
elif len(sys.argv) == 3 and sys.argv[1] == "--export-preview":
pathlib.Path(sys.argv[2]).write_text(json.dumps(preview_pages(), ensure_ascii=False), encoding="utf-8")
else:
unittest.main()
+1 -1
View File
@@ -28,7 +28,7 @@ const html = template.replace('window.ROUTERS = [];', 'window.ROUTERS = '+JSON.s
if (url.pathname === '/api/router-groups') return route.fulfill({json:{groups:[]}});
if (url.pathname === '/api/notifications/wait') return route.fulfill({status:429,json:{busy:true},headers:{'Retry-After':'5'}});
if (url.pathname === '/api/vps/resources') return route.fulfill({json:{ok:true,cpu:{percent:15},memory:{percent:35},disk:{percent:40}}});
if (url.pathname === '/api/hub-update') return route.fulfill({json:{ok:true,checked:true,available:false,current_version:'v121'}});
if (url.pathname === '/api/hub-update') return route.fulfill({json:{ok:true,checked:true,available:false,current_version:'v122'}});
if (url.pathname.startsWith('/api/')) return route.fulfill({json:{ok:true,auth:{username:'root',is_owner:true,can_add_router:true}}});
return route.abort();
});
+1 -1
View File
@@ -71,7 +71,7 @@ class UpdateTests(unittest.TestCase):
self.assertEqual(fetch.call_args.args[0].full_url, source + '/vps/owrt-remote-hub.py')
data = self.manager.snapshot()
self.assertTrue(data['available'])
self.assertEqual(data['remote_version'], 'v121')
self.assertEqual(data['remote_version'], 'v122')
self.assertEqual(data['remote_revision'], hashlib.sha256(NEW).hexdigest())
self.assertEqual(self.target.read_bytes(), SOURCE)
+1 -1
View File
@@ -10,7 +10,7 @@ execFileSync(process.env.TEST_PYTHON || 'python', ['tests/test_vps_resources.py'
const pageHtml = fs.readFileSync(path.join(output, 'dashboard.html'), 'utf8');
function state() {
return {ok:true,checked:true,checking:false,error:'',source:'https://raw.githubusercontent.com/kzolotarev95/luci-app-owrt-remote/main',
current_revision:'a'.repeat(64),current_version:'v121',remote_revision:'b'.repeat(64),remote_version:'v121',source_older:false,available:true,job:{},csrf:'test-csrf'};
current_revision:'a'.repeat(64),current_version:'v122',remote_revision:'b'.repeat(64),remote_version:'v122',source_older:false,available:true,job:{},csrf:'test-csrf'};
}
async function createFixture(browser,width,height,mobile) {
const page = await browser.newPage({viewport:{width,height},isMobile:mobile,hasTouch:mobile});
+73
View File
@@ -97,5 +97,78 @@ esac
self.assertEqual(calls.read_text().splitlines(),['rpcd running','rpcd '+operation,
'uhttpd running','uhttpd '+operation])
def dependencies_driver(self, fail=False):
source=self.installer.read_text(encoding='utf-8').split('# Stop the old log writer')[0]
source=source.replace('/etc/ssl/cert.pem', self.root.joinpath('cert.pem').as_posix())
source=source.replace('/etc/ssl/certs/ca-certificates.crt', self.root.joinpath('ca.crt').as_posix())
source+='''
ROOT=/
command() {
if [ "$1" = -v ]; then
case "$2" in curl|jsonfilter) [ -f "$TMPDIR/deps-ready" ]; return $? ;; esac
fi
builtin command "$@"
}
package_manager() { printf apk; }
install_packages() {
printf '%s\\n' "$*" >"$TMPDIR/packages"
[ "$DEPS_FAIL" != 1 ] || { echo 'apk repository unavailable' >&2; return 19; }
printf CA >"$TMPDIR/ca.crt"; touch "$TMPDIR/deps-ready"
}
ensure_install_dependencies
echo DEPENDENCIES_READY
'''
script=self.root/'deps.sh'; script.write_text(source,encoding='utf-8',newline='\n')
return subprocess.run(self.args+[script.as_posix()],capture_output=True,encoding='utf-8',timeout=20,
env={**self.env,'DEPS_FAIL':'1' if fail else '0'})
def test_missing_curl_ca_jsonfilter_are_prepared_with_apk_before_files(self):
result=self.dependencies_driver()
self.assertEqual(result.returncode,0,result.stderr)
self.assertEqual(self.root.joinpath('packages').read_text().split(), ['curl','jsonfilter','ca-certificates'])
self.assertIn('DEPENDENCIES_READY',result.stdout)
def test_dependency_failure_has_separate_stage_and_never_reaches_xray(self):
result=self.dependencies_driver(fail=True)
self.assertNotEqual(result.returncode,0)
self.assertIn('stage=dependencies',result.stderr)
self.assertIn('apk repository unavailable',result.stderr)
self.assertNotIn('DEPENDENCIES_READY',result.stdout)
def runtime_driver(self, rc):
installer=self.installer.read_text(encoding='utf-8')
prefix=installer.split('# Stop the old log writer')[0]
main=installer.split('\ninstall_xray_runtime\n',1)[1].split('\nkey=',1)[0]
agent=self.root/'agent'
agent.write_text('''#!/bin/sh
echo "$1" >>"$TMPDIR/agent-calls"
[ "$TEST_PREPARE_RC" = 0 ] || echo 'download failed: reason=DNS' >&2
exit "$TEST_PREPARE_RC"
''',encoding='utf-8',newline='\n')
agent.chmod(0o755)
source=prefix+'''
ROOT=/
target_path() { printf '%s/agent' "$TMPDIR"; }
uci() { printf 0; }
install_xray_runtime
'''+main+'\necho FIRST_INSTALL_FINISHED\n'
script=self.root/'runtime.sh';script.write_text(source,encoding='utf-8',newline='\n')
return subprocess.run(self.args+[script.as_posix()],env={**self.env,'TEST_PREPARE_RC':str(rc)},
capture_output=True,encoding='utf-8',timeout=20)
def test_prepared_first_install_without_hub_config_finishes_successfully(self):
result=self.runtime_driver(0)
self.assertEqual(result.returncode,0,result.stderr)
self.assertIn('Установлено. Добавьте OpenWrt config из Hub для запуска туннеля',result.stdout)
self.assertIn('FIRST_INSTALL_FINISHED',result.stdout)
self.assertEqual(self.root.joinpath('agent-calls').read_text().splitlines(),['prepare-xray'])
def test_prepare_failure_keeps_original_rc_at_installer_boundary(self):
result=self.runtime_driver(6)
self.assertEqual(result.returncode,6,result.stderr)
self.assertIn('stage=prepare-xray rc=6',result.stderr)
self.assertIn('reason=DNS',result.stderr)
self.assertNotIn('FIRST_INSTALL_FINISHED',result.stdout)
if __name__=='__main__': unittest.main()
+1 -1
View File
@@ -102,7 +102,7 @@ logger() { printf '%s\\n' "$3" | sh "$TEST_LOG_HELPER" append; }
self.assertIn('PERSISTENT_LOGS_ROUTER_Install_OK', result.stdout)
for item in ('cgi', 'luci'):
installed = self.root / self.targets[item].lstrip('/')
self.assertIn('v121', installed.read_text(encoding='utf-8'))
self.assertIn('v122', installed.read_text(encoding='utf-8'))
for item, data in self.initial.items():
self.assertEqual(self.backup.joinpath(item).read_bytes(), data)
result = self.deploy('Rollback')
+1 -1
View File
@@ -131,7 +131,7 @@ class HubFixture:
assert "groups" in json.loads(self.request("/api/router-groups"))
assert "notifications" in json.loads(self.request("/api/notifications"))
assert self.request("/access/test-router/") == b"router proxy fixture"
assert b"v121" in self.request("/")
assert b"v122" in self.request("/")
self.app.snapshot_router_states()
def __exit__(self, *args):
+202
View File
@@ -0,0 +1,202 @@
"""Download failures, fallback, budgets and preservation; no public network."""
import os
from pathlib import Path
import shlex
import subprocess
import time
import unittest
import test_xray_bootstrap as base
class DownloaderTests(unittest.TestCase):
config = base.XrayBootstrapTests.config
shell = base.XrayBootstrapTests.raw_shell
def setUp(self):
base.XrayBootstrapTests.setUp(self)
if os.name == 'nt':
self.clients += '\nulimit() { [ "$1 $2" = "-f 32768" ]; }\n'
tools = self.directory / 'tools'
tools.mkdir()
native = tools / 'uclient-fetch'
native.write_text('#!/bin/sh\n' + self.clients + '\nuclient_fetch_mock "$@"\n',
encoding='utf-8', newline='\n')
native.chmod(0o755)
self.env['PATH'] = tools.as_posix() + os.pathsep + self.env['PATH']
clients = r'''
command() {
if [ "$1" = -v ]; then
case "$2" in curl|wget|uclient-fetch)
case " $TEST_TOOLS " in *" $2 "*) printf '%s\n' "$2"; return 0 ;; *) return 1 ;; esac ;;
esac
fi
builtin command "$@"
}
curl() {
printf 'curl\n' >>"$TEST_ROOT/clients"
local previous arg output
previous=''
for arg in "$@"; do [ "$previous" != -o ] || output="$arg"; previous="$arg"; done
printf partial >"$output"
[ "${CURL_RC:-6}" = 0 ] || { printf 'could not resolve SECRET_URL\n' >&2; return "${CURL_RC:-6}"; }
printf payload >"$output"; printf '200 \n'
}
uclient_fetch_mock() {
printf 'uclient-fetch\n' >>"$TEST_ROOT/clients"
local previous arg output
previous=''
for arg in "$@"; do [ "$previous" != -O ] || output="$arg"; previous="$arg"; done
printf partial >"$output"
[ "${NATIVE_RC:-0}" = 0 ] || { printf 'TLS certificate error\n' >&2; return "$NATIVE_RC"; }
printf payload >"$output"
}
wget() { printf 'wget\n' >>"$TEST_ROOT/clients"; uclient_fetch_mock "$@"; }
'''
def download(self, extra='', **env):
return self.shell('fetch_file "https://github.com/test?token=SECRET_TOKEN" "$TEST_ROOT/download"',
mocks=self.clients + extra, TEST_TOOLS='curl uclient-fetch wget', **env)
def test_curl_failure_switches_to_next_client_without_leaking_stderr_or_url(self):
result = self.download()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.directory / 'download').read_text(), 'payload')
self.assertEqual((self.directory / 'clients').read_text().splitlines(), ['curl', 'uclient-fetch'])
self.assertIn('reason=DNS', result.stderr)
self.assertIn('tool=uclient-fetch', result.stderr)
self.assertNotIn('SECRET', result.stderr)
self.assertFalse(list(self.directory.glob('owrt-download.*')))
def test_native_failure_keeps_original_rc_and_tls_reason(self):
result = self.shell('fetch_file https://github.com/test "$TEST_ROOT/download"',
mocks=self.clients, TEST_TOOLS='uclient-fetch', NATIVE_RC='7')
self.assertEqual(result.returncode, 7, result.stderr)
self.assertIn('rc=7; reason=TLS', result.stderr)
self.assertFalse((self.directory / 'download').exists())
def test_wget_symlink_to_uclient_is_not_a_second_attempt(self):
result = self.download(extra=r'''
readlink() { case "$2" in wget|uclient-fetch) printf /bin/uclient-fetch ;; *) printf '%s' "$2" ;; esac; }
''', NATIVE_RC='1')
self.assertNotEqual(result.returncode, 0)
self.assertEqual((self.directory / 'clients').read_text().splitlines(), ['curl', 'uclient-fetch'])
def test_expired_preparation_budget_prevents_all_requests(self):
result = self.download(XRAY_PREPARE_DEADLINE='1')
self.assertEqual(result.returncode, 28, result.stderr)
self.assertFalse((self.directory / 'clients').exists())
def test_write_error_does_not_retry_another_client(self):
result = self.download(CURL_RC='23')
self.assertEqual(result.returncode, 23)
self.assertIn('reason=write', result.stderr)
self.assertEqual((self.directory / 'clients').read_text().splitlines(), ['curl'])
def test_no_head_gate_in_candidate_install(self):
data = base.XrayBootstrapTests.make_binary(self)
self.directory.joinpath('release.pkg').write_bytes(data)
result = base.XrayBootstrapTests.shell(self, 'install_xray_tmp', mocks=r'''
xray_probe_url() { echo forbidden-HEAD >&2; return 22; }
fetch_file() { cp "$TEST_ROOT/release.pkg" "$2"; }
''')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn('forbidden-HEAD', result.stderr)
def test_network_failure_does_not_search_old_releases_or_report_incompatibility(self):
data = base.XrayBootstrapTests.make_binary(self)
self.directory.joinpath('release.pkg').write_bytes(data)
result = base.XrayBootstrapTests.shell(self, 'install_xray_tmp', mocks=r'''
xray_discover_releases() {
printf '2\n' >"$2/next-release-page"
for asset in first second third; do
printf 'v26.6.27|%s.ipk|https://github.com/%s|%s|%s\n' "$asset" "$asset" "$(xray_digest "$TEST_ROOT/release.pkg")" "$(wc -c <"$TEST_ROOT/release.pkg")"
done >"$1"
}
fetch_file() { echo "$1" >>"$TEST_ROOT/clients"; return 6; }
''')
self.assertEqual(result.returncode, 6, result.stderr)
self.assertEqual(len(self.directory.joinpath('clients').read_text().splitlines()), 1)
self.assertIn('published Xray package found but download failed', result.stderr)
self.assertNotIn('No compatible', result.stderr)
self.assertTrue(self.binary.exists())
def test_prepare_preserves_original_download_return_code(self):
result = self.shell('prepare_xray', mocks='ensure_xray_available() { return 6; }')
self.assertEqual(result.returncode, 6, result.stderr)
def mirror_install(self, corrupt=False):
good = base.XrayBootstrapTests.make_binary(self, 'working')
cached = base.XrayBootstrapTests.cache(self, good)
candidate = base.XrayBootstrapTests.make_binary(self, 'new')
self.binary.write_bytes(good)
self.directory.joinpath('release.pkg').write_bytes(candidate)
result = base.XrayBootstrapTests.shell(self, 'install_xray_tmp', mocks=r'''
fetch_file() {
printf '%s %s\n' "$1" "$XRAY_FILE_DEADLINE" >>"$TEST_ROOT/clients"
case "$1" in https://mirror.example/*)
if [ "$TEST_CORRUPT" = 1 ]; then tr X Y <"$TEST_ROOT/release.pkg" >"$2"; else cp "$TEST_ROOT/release.pkg" "$2"; fi ;;
*) return 6 ;;
esac
}
''', XRAY_PACKAGE_MIRROR='https://mirror.example/xray', TEST_CORRUPT='1' if corrupt else '0')
return result, good, candidate, cached
def test_opt_in_mirror_uses_same_file_deadline_and_official_digest(self):
result, good, candidate, _ = self.mirror_install()
self.assertEqual(result.returncode, 0, result.stderr)
calls = self.directory.joinpath('clients').read_text().splitlines()
self.assertIn('https://mirror.example/xray/v26.6.27/test.ipk', calls[-1])
self.assertEqual(calls[0].split()[-1], calls[-1].split()[-1])
self.assertEqual(self.binary.read_bytes(), candidate)
def test_corrupted_mirror_file_cannot_replace_binary_or_boot_cache(self):
result, good, candidate, cached = self.mirror_install(corrupt=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn('SHA256 mismatch', result.stderr)
self.assertEqual(self.binary.read_bytes(), good)
self.assertTrue(cached.exists())
def test_embedded_install_and_agent_downloaders_match_the_single_source(self):
root = Path(__file__).resolve().parents[1]
result = subprocess.run([os.sys.executable, str(root / 'scripts/embed-router-download.py'), '--check'],
capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
@unittest.skipIf(os.name == 'nt', 'Linux /proc process-tree watchdog integration')
def test_hung_client_is_killed_and_reaped_before_native_fallback(self):
started = time.monotonic()
result = self.shell('XRAY_FILE_DEADLINE=$(( $(download_clock) + 6 )); fetch_file https://github.com/test "$TEST_ROOT/download"',
mocks=self.clients + r'''
curl() {
read -r child rest </proc/self/stat
printf '%s\n' "$child" >"$TEST_ROOT/hung-pid"
command sleep 30
}
''', TEST_TOOLS='curl uclient-fetch')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertLess(time.monotonic() - started, 9)
pid = int(self.directory.joinpath('hung-pid').read_text())
self.assertFalse(Path('/proc', str(pid)).exists(), 'HTTP child was not reaped')
self.assertEqual(self.directory.joinpath('download').read_text(), 'payload')
@unittest.skipIf(os.name == 'nt', 'Linux ash TERM/EXIT trap integration')
def test_preparation_deadline_runs_worker_cleanup_and_preserves_working_binary(self):
good = base.XrayBootstrapTests.make_binary(self)
result = self.shell('XRAY_PREPARE_DEADLINE=$(( $(download_clock) + 2 )); xray_prepare_timed hung_preparation',
mocks=r'''
hung_preparation() (
trap 'rm -f "$TEST_ROOT/temporary-work"' EXIT
trap 'exit 1' TERM INT
touch "$TEST_ROOT/temporary-work"
command sleep 30
)
''')
self.assertEqual(result.returncode, 28, result.stderr)
self.assertFalse(self.directory.joinpath('temporary-work').exists())
self.assertEqual(self.binary.read_bytes(), good)
if __name__ == '__main__':
unittest.main()
+297
View File
@@ -0,0 +1,297 @@
"""Per-router discovery lifecycle, authenticated proxy and fixed reverse targets."""
import http.client
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
import re
from pathlib import Path
import subprocess
import tempfile
import threading
from types import SimpleNamespace
import unittest
from unittest import mock
import test_host_policy as base
hub = base.hub
def detected(**values):
return dict(checked=True, installed=True, version='2.0.0~beta.8-1',
mode='standalone', port=1680, service='running', available=True, **values)
class StateTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.db = Path(self.temp.name) / 'hub.db'
self.context = hub.connect(self.db)
self.conn = self.context.__enter__()
hub.init_db(self.conn)
self.addCleanup(self.context.__exit__, None, None, None)
for rid, port in [('a', 18080), ('b', 18081)]:
hub.upsert_router(self.conn, dict(id=rid, entry_port=port))
def beat(self, rid='a', tachyon=None):
return hub.heartbeat(self.conn, dict(id=rid, xray='running', tachyon=tachyon))
def test_independent_install_stop_remove_reinstall_and_network_recovery(self):
a = self.beat(tachyon=detected())
self.assertTrue(a['tachyon']['online'])
self.assertNotIn('tachyon', self.beat('b', {'checked': True, 'installed': False}))
port = a['tachyon_entry_port']
self.assertTrue(a['_xray_reload_required'])
value = detected(); value.update(service='stopped', available=False)
a = self.beat(tachyon=value)
self.assertFalse(a['tachyon']['online'])
self.assertFalse(a['_xray_reload_required'], 'service status must not restart every tunnel')
self.assertEqual(a['tachyon']['url'], '/tachyon/a/')
a = self.beat(tachyon={'checked': False})
self.assertIn('tachyon', a, 'inventory error is not uninstall')
self.assertFalse(a['tachyon']['online'])
a = self.beat(tachyon={'checked': True, 'installed': False})
self.assertNotIn('tachyon', a)
self.assertTrue(a['_xray_reload_required'])
a = self.beat(tachyon=detected())
self.assertEqual(a['tachyon_entry_port'], port)
self.conn.execute("update routers set last_seen=1 where id='a'")
self.assertFalse(hub.row_to_router(hub.get_router(self.conn, 'a'))['tachyon']['online'])
self.assertTrue(self.beat(tachyon=detected())['tachyon']['online'])
def test_bad_endpoints_never_create_arbitrary_target(self):
for patch in ({'port': 22}, {'port': '1680'}, {'port': 65536}, {'mode': 'http://evil'},
{'port': True}, {'checked': 'true'}, {'installed': 'true'}):
value = detected(); value.update(patch)
self.assertIsNone(hub.normalize_tachyon(value), patch)
value = detected(); value.update(host='169.254.169.254', token='SECRET')
clean = hub.normalize_tachyon(value)
self.assertNotIn('host', clean); self.assertNotIn('token', clean)
def test_both_generators_share_fixed_loopback_target_and_existing_reverse(self):
a = self.beat(tachyon=detected())
row = hub.get_router(self.conn, 'a')
server = hub.make_server_xray_config([row])
inbound = next(i for i in server['inbounds'] if i['tag'] == 'tachyon-a')
self.assertEqual(inbound['listen'], '127.0.0.1')
self.assertEqual(inbound['settings']['rewriteAddress'], '127.0.0.1')
self.assertEqual(inbound['settings']['rewritePort'], 1680)
self.assertEqual(inbound['settings']['address'], inbound['settings']['rewriteAddress'])
self.assertEqual(inbound['settings']['port'], inbound['settings']['rewritePort'])
self.assertEqual(inbound['settings']['network'], 'tcp')
client = hub.make_router_xray_config(row)
rule = client['routing']['rules'][0]
self.assertEqual(rule['outboundTag'], 'router-tachyon')
self.assertEqual(rule['ip'], ['127.0.0.1'])
self.assertEqual(client['outbounds'][0]['settings']['redirect'], '127.0.0.1:1680')
self.assertEqual(len(server['inbounds'][0]['settings']['clients']), 2)
self.assertEqual(hub.get_router_by_any_port(self.conn, a['tachyon_entry_port'])['id'], 'a')
with self.assertRaisesRegex(ValueError, 'Tachyon'):
hub.upsert_router(self.conn, {'id': 'a', 'entry_port': a['tachyon_entry_port']})
def test_legacy_luci_uses_existing_admin_tunnel(self):
value = detected(); value.update(mode='luci', port=0, version='1.3.13')
self.beat(tachyon=value)
self.assertFalse(any(i['tag'] == 'tachyon-a' for i in hub.make_server_xray_config([hub.get_router(self.conn, 'a')])['inbounds']))
def test_existing_report_with_no_entry_port_still_requests_server_reload(self):
self.conn.execute("update routers set status_json=? where id='a'", (json.dumps({'tachyon': detected()}),))
self.conn.commit()
router = self.beat(tachyon=detected())
self.assertGreater(router['tachyon_entry_port'], 0)
self.assertTrue(router['_xray_reload_required'])
def test_rewrite_keeps_api_and_assets_inside_selected_router(self):
body = b'<html><head></head><body><script>fetch("/api/login");fetch("/ubus");</script><img src="/assets/icon.png"></body></html>'
rendered = hub.rewrite_html(body, '/tachyon/a', 'text/html').decode()
for path in ('/api/login', '/ubus', '/assets/icon.png'):
self.assertIn('/tachyon/a' + path, rendered)
self.assertNotIn('/tachyon/a/api/login', hub.rewrite_html(body, '/access/a', 'text/html').decode())
@unittest.skipUnless(base.SH, 'POSIX shell required')
class DiscoveryTests(unittest.TestCase):
def setUp(self):
self.harness = base.RouterShellTests()
self.harness.setUp()
self.addCleanup(self.harness.doCleanups)
self.harness.config(vps_host='hub.example', vless_uuid='11111111-1111-4111-8111-111111111111')
self.root = self.harness.directory
self.harness.env.update(OWRT_REMOTE_TACHYON_HELPER=str(base.ROOT / 'files/usr/lib/owrt-remote/tachyon.sh').replace('\\', '/'),
OWRT_REMOTE_TACHYON_RUNTIME=self.root.as_posix() + '/tachyon')
if os.environ.get('TACHYON_TEST_BUSYBOX'):
def busybox_shell(command, **env):
mocks = re.sub(r'(?ms)^owrt-remote\(\) \{.*?^\}\n', '', base.MOCKS)
return subprocess.run([os.environ['TACHYON_TEST_BUSYBOX'], 'ash'],
input=self.harness.agent + '\n' + mocks + '\n' + command,
env={**self.harness.env, **env}, cwd=base.ROOT, capture_output=True,
encoding='utf-8', timeout=60)
self.harness.run_shell = busybox_shell
self.mocks = r'''
opkg() {
[ ! -e "$TEST_ROOT/inventory-error" ] || return 1
[ ! -e "$TEST_ROOT/absent" ] || return 0
printf 'Package: tachyon\nVersion: %s\nStatus: install user installed\n' "$TEST_VERSION"
}
curl() {
[ "$TEST_HTTP" != fail ] || return 7
for last do :; done
case "$last" in
*/api/agent/v1/health) printf '{"core_running":false}' ;;
*/api/agent/v1/openapi.json) printf '{"info":{"version":"2.0.0-beta.14"}}' ;;
*) printf '%s' "$TEST_HTTP" ;;
esac
}
ubus() { printf '{"running":%s}' "$TEST_SERVICE"; }
jsonfilter() {
"$TEST_PYTHON" -c 'import sys,json
a=sys.argv[1:]; data=json.load(open(a[1])) if a and a[0]=="-i" else json.load(sys.stdin)
path=a[-1]
if "instances" in path: value=data.get("running")
elif "router-tachyon" in path: value=next((o["settings"]["redirect"] for o in data.get("outbounds",[]) if o["tag"]=="router-tachyon"),"")
else:
value=data
for key in path.removeprefix("@.").split("."): value=value.get(key,"") if isinstance(value,dict) else ""
print(str(value).lower() if isinstance(value,bool) else value)' "$@"
}
'''
def run_shell(self, command, **env):
return self.harness.run_shell(self.mocks + command, TEST_VERSION='2.0.0~beta.8-1',
TEST_HTTP='200', TEST_SERVICE='true', **env)
def test_opkg_present_http_offline_inventory_failure_and_uninstall(self):
result = self.run_shell('tachyon_json force')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(result.stdout)['port'], 1680)
self.assertEqual(json.loads(result.stdout)['api'], '/api/agent/v1')
self.assertEqual(json.loads(result.stdout)['version'], '2.0.0-beta.14')
self.assertEqual(json.loads(result.stdout)['package_version'], '2.0.0~beta.8-1')
self.assertTrue(json.loads(result.stdout)['available'])
result = self.harness.run_shell(self.mocks + 'tachyon_json force', TEST_VERSION='2.0.0', TEST_HTTP='fail', TEST_SERVICE='false')
self.assertTrue(json.loads(result.stdout)['installed'])
self.assertFalse(json.loads(result.stdout)['available'])
self.root.joinpath('inventory-error').touch()
self.assertFalse(json.loads(self.run_shell('tachyon_json force').stdout)['checked'])
self.root.joinpath('inventory-error').unlink()
self.root.joinpath('absent').touch()
self.assertEqual(json.loads(self.run_shell('tachyon_json force').stdout), dict(checked=True, installed=False))
self.assertFalse(list(self.root.glob('tachyon/probe.*')))
def test_apk_discovery_and_legacy_luci(self):
code = r'''
apk() { if [ "$2" = -v ]; then echo tachyon-2.0.0-r1; else printf 'base-files\ntachyon\n'; fi; }
tachyon_json force
'''
result = self.run_shell(code)
self.assertEqual(json.loads(result.stdout)['package_version'], '2.0.0-r1')
with (self.root / 'uci').open('a') as config:
config.write('tachyon.settings.listen_port=1602\n')
result = self.harness.run_shell(self.mocks + 'tachyon_json force', TEST_VERSION='1.3.13', TEST_HTTP='403', TEST_SERVICE='true')
self.assertEqual(json.loads(result.stdout)['mode'], 'luci')
self.assertEqual(json.loads(result.stdout)['port'], 0)
def test_custom_web_port_and_no_reconfigure_when_manually_stopped(self):
with (self.root / 'uci').open('a') as config:
config.write('tachyon.settings.listen_port=1800\n')
result = self.run_shell('tachyon_json force')
self.assertEqual(json.loads(result.stdout)['port'], 1800)
self.harness.config(enabled='1')
result = self.run_shell(r'''
xray_control_stopped() { return 0; }
xray_running() { return 0; }
ubus() { echo unexpected >>"$TEST_ROOT/changed"; }
tachyon_reconcile_xray
''')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse((self.root / 'changed').exists())
def test_shell_generator_matches_tachyon_route(self):
result = self.run_shell('render_client_config --stdout')
self.assertEqual(result.returncode, 0, result.stderr)
config = json.loads(result.stdout)
self.assertEqual(config['outbounds'][0]['settings']['redirect'], '127.0.0.1:1680')
self.assertEqual(config['routing']['rules'][0]['outboundTag'], 'router-tachyon')
class ProxyTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.app = hub.App(Path(self.temp.name) / 'hub.db', 'session-test', 'agent-test', '')
hub.write_json_private(hub.AUTH_FILE, {'username': 'owner', 'password_hash': 'unused'})
class Backend(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/layout':
data = b'<html><head><style>.tachyon-bg-layer{position:fixed;inset:0}</style></head><body><div class="tachyon-bg-layer"></div><main>Tachyon</main></body></html>'
self.send_response(200); self.send_header('Content-Type', 'text/html')
self.send_header('Content-Length', str(len(data))); self.end_headers(); self.wfile.write(data)
return
data = json.dumps({'path': self.path, 'cookie': self.headers.get('Cookie', ''),
'method': self.command, 'body': self.rfile.read(int(self.headers.get('Content-Length', 0))).decode()}).encode()
self.send_response(200); self.send_header('Content-Type', 'application/json')
self.send_header('Set-Cookie', 'tachyon_session=test-private; Path=/; HttpOnly')
self.send_header('Content-Length', str(len(data))); self.end_headers(); self.wfile.write(data)
do_POST = do_GET
do_PUT = do_GET
do_DELETE = do_GET
def log_message(self, *args): pass
self.backend = ThreadingHTTPServer(('127.0.0.1', 0), Backend)
self.server = hub.HubHTTPServer(('127.0.0.1', 0), hub.Handler)
self.server.app = self.app; self.server.is_tls = False
for server in (self.backend, self.server):
thread = threading.Thread(target=server.serve_forever, daemon=True); thread.start()
self.addCleanup(self.close, server, thread)
with self.app.conn() as conn:
hub.upsert_router(conn, {'id': 'main', 'entry_port': 18880})
hub.heartbeat(conn, {'id': 'main', 'tachyon': detected()})
conn.execute("update routers set tachyon_entry_port=? where id='main'", (self.backend.server_port,))
hub.upsert_router(conn, {'id': 'absent'})
@staticmethod
def close(server, thread):
server.shutdown(); server.server_close(); thread.join(timeout=3)
def request(self, path='/tachyon/main/', method='GET', origin=None, cookie=True):
headers = {}
if cookie: headers['Cookie'] = 'owrt_remote_session=session-test; tachyon_session=private-router-session'
if origin: headers['Origin'] = origin
connection = http.client.HTTPConnection('127.0.0.1', self.server.server_port, timeout=5)
try:
connection.request(method, path, body='{}' if method != 'GET' else None, headers=headers)
with connection.getresponse() as result: return result.status, result.read(), result.getheaders()
finally: connection.close()
def test_proxy_authentication_selected_router_cookie_scope_and_mutations(self):
self.assertEqual(self.request(cookie=False)[0], 401)
status, raw, headers = self.request('/tachyon/main/api/status?view=x')
self.assertEqual(status, 200, raw)
result = json.loads(raw)
self.assertEqual(result['path'], '/api/status?view=x')
self.assertNotIn('session-test', result['cookie'])
self.assertIn('private-router-session', result['cookie'])
cookie = next(v for k, v in headers if k.lower() == 'set-cookie')
self.assertIn('Path=/tachyon/main/', cookie)
self.assertEqual(self.request('/tachyon/absent/')[0], 404)
self.assertEqual(self.request('/tachyon/missing/')[0], 404)
with mock.patch.object(hub.Handler, 'router_access_allowed', return_value=False):
self.assertEqual(self.request()[0], 403)
self.assertEqual(self.request(method='POST', origin='https://foreign.example')[0], 403)
origin = 'http://127.0.0.1:' + str(self.server.server_port)
for method in ('POST', 'PUT', 'DELETE'):
status, raw, _ = self.request('/tachyon/main/api/settings', method, origin)
self.assertEqual(status, 200, raw)
self.assertEqual(json.loads(raw)['method'], method)
self.assertEqual(json.loads(raw)['body'], '{}')
def test_tachyon_html_keeps_own_layout_without_shared_hub_effects(self):
status, raw, _ = self.request('/tachyon/main/layout')
self.assertEqual(status, 200)
self.assertNotIn(b'owrt-hub-design-head', raw)
self.assertNotIn(b'body>*:not(.seasonalFx)', raw)
self.assertIn(b'.tachyon-bg-layer{position:fixed;inset:0}', raw)
self.assertIn(b'const prefix = "/tachyon/main"', raw, 'URL forwarding still applies')
if __name__ == '__main__':
unittest.main()
+102
View File
@@ -0,0 +1,102 @@
"""Exercise install/rollback and failure recovery in a disposable router tree."""
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import tempfile
import unittest
from test_host_policy import ROOT, SH
@unittest.skipUnless(SH, 'POSIX shell required')
class DeployTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix='tachyon-deploy-')
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.env = dict(os.environ)
if os.name == 'nt':
self.env['PATH'] = str(Path(SH).parent) + os.pathsep + self.env['PATH']
self.targets = {name: self.root / name for name in ('agent', 'tachyon.sh')}
for name in ('agent',):
self.targets[name].write_text('#!/bin/sh\necho previous\n')
self.before = {name: path.read_bytes() if path.exists() else None for name, path in self.targets.items()}
self.script = (ROOT / 'vps/deploy-tachyon.ps1').read_text().split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
self.script = self.script.replace('backup=/root/owrt-remote-backup-before-__BACKUP_NAME__-v121', 'backup=' + shlex.quote((self.root / 'backup').as_posix()))
for name, target in self.targets.items():
original = {'agent': '/usr/sbin/owrt-remote', 'tachyon.sh': '/usr/lib/owrt-remote/tachyon.sh'}[name]
self.script = self.script.replace('echo ' + original, 'echo ' + shlex.quote(target.as_posix()))
self.script = self.script.replace('/etc/init.d/owrt-remote restart', 'test_restart')
mocks = '''
ubus() { printf '{}'; }
jsonfilter() { printf true; }
timeout() { return 0; }
busybox() { return 127; }
test_restart() { [ "${FAIL_RESTART:-0}" != 1 ]; }
sleep() { :; }
'''
self.script = mocks + self.script.replace('test -r /usr/lib/owrt-remote/control.sh', 'true')
def deploy(self, action='Install', bad=False, fail=False, no_timeout=False):
stage = self.root / 'stage'
stage.mkdir()
for name, source in {'agent': 'files/usr/sbin/owrt-remote', 'tachyon.sh': 'files/usr/lib/owrt-remote/tachyon.sh'}.items():
text = 'if true; then\n' if bad and name == 'tachyon.sh' else (ROOT / source).read_text(encoding='utf-8')
stage.joinpath(name).write_text(text, encoding='utf-8', newline='\n')
script = self.script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(stage.as_posix()))
script = script.replace('__UPLOAD_NAME__', 'sandbox').replace('__KIND__', 'Router').replace('__ACTION__', action)
if no_timeout:
# Model the optional applet missing from both PATH and BusyBox.
script = script.replace('command -v timeout >/dev/null 2>&1', 'false')
result = subprocess.run([SH], input=script, text=True, encoding='utf-8', capture_output=True,
env={**self.env, 'FAIL_RESTART': str(int(fail))}, timeout=30)
self.assertFalse(stage.exists())
self.assertFalse(list(self.root.glob('*.new-sandbox')))
return result
def assert_original(self):
for name, path in self.targets.items():
self.assertEqual(path.read_bytes() if path.exists() else None, self.before[name])
def test_install_twice_and_rollback_restore_absent_helper(self):
for _ in range(2):
result = self.deploy()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('TACHYON_INTEGRATION_Router_Install_OK', result.stdout)
result = self.deploy('Rollback')
self.assertEqual(result.returncode, 0, result.stderr)
self.assert_original()
def test_invalid_candidate_and_missing_backup_do_not_change_files(self):
self.assertNotEqual(self.deploy(bad=True).returncode, 0)
self.assert_original()
self.assertNotEqual(self.deploy('Rollback').returncode, 0)
self.assert_original()
def test_restart_failure_restores_files_from_current_attempt(self):
result = self.deploy(fail=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn('restoring files', result.stderr)
self.assertIn('Failed during restart', result.stderr)
self.assertIn('Router deployment diagnostics:', result.stderr)
self.assert_original()
def test_missing_timeout_applet_does_not_reject_router(self):
result = self.deploy(no_timeout=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('shell timeout fallback will be used', result.stderr)
self.assertIn('TACHYON_INTEGRATION_Router_Install_OK', result.stdout)
def test_failed_preflight_names_step_and_keeps_files(self):
result = self.deploy(bad=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn('tachyon.sh shell syntax check failed', result.stderr)
self.assertIn('Failed during preflight', result.stderr)
self.assertNotIn('restoring files', result.stderr)
self.assert_original()
if __name__ == '__main__':
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
// Requires Playwright; see docs/TACHYON_INTEGRATION.md for the layout scenario.
const { chromium } = require('playwright');
const fs = require('node:fs');
const assert = require('node:assert/strict');
const fixtures = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
(async () => {
const browser = await chromium.launch({
headless: true,
...(process.env.OWRT_TEST_BROWSER_BIN ? {executablePath: process.env.OWRT_TEST_BROWSER_BIN} : {})
});
let count = 0;
try {
for (const [fixture, body] of Object.entries(fixtures)) {
for (const [width, height] of [[1280,900], [390,844], [844,390]]) {
for (const design of ['default','winter','lite']) {
const context = await browser.newContext({viewport: {width,height}});
try {
await context.addInitScript(mode => {
localStorage.setItem('owrtRemote:hubDesign', mode);
localStorage.setItem('owrtRemote:seasonEffectMode', 'snow');
}, design);
await context.route('**/*', route => {
if (route.request().isNavigationRequest()) return route.fulfill({status:200, contentType:'text/html', body});
return route.abort(); // Layout check only: no RPC or router writes.
});
const page = await context.newPage();
await page.goto('http://hub.test/tachyon/node-10/', {waitUntil:'domcontentloaded'});
await page.waitForTimeout(80);
const geometry = await page.evaluate(() => ({
backgroundPosition: getComputedStyle(document.querySelector('.tachyon-bg-layer')).position,
contentTop: document.querySelector('#maincontent').getBoundingClientRect().top,
scrollY: window.scrollY,
extraCanvas: Boolean(document.getElementById('seasonalFx'))
}));
const label = [fixture,width,height,design].join('/');
assert.equal(geometry.backgroundPosition,'fixed',label);
assert(geometry.contentTop >= -1 && geometry.contentTop <= 1, label + ': content pushed down: ' + geometry.contentTop);
assert.equal(geometry.scrollY,0,label);
assert.equal(geometry.extraCanvas,false,label);
count++;
} finally { await context.close(); }
}
}
}
} finally { await browser.close(); }
console.log('TACHYON_LAYOUT_OK: ' + count + ' browser cases; content starts at the top');
})().catch(error => {console.error(error);process.exitCode=1;});
+105
View File
@@ -0,0 +1,105 @@
"""Hub and Xray must be validated and restored as one local deployment."""
import os
import json
from pathlib import Path
import shlex
import subprocess
import sys
import tempfile
import unittest
from test_host_policy import ROOT, SH
@unittest.skipUnless(SH, 'POSIX shell required')
class RouteDeployTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.hub = self.root / 'hub.py'
self.xray = self.root / 'xray.json'
self.hub.write_text('old hub')
self.xray.write_text('old xray')
self.env = {**os.environ, 'PATH': str(Path(SH).parent) + os.pathsep + os.environ['PATH']}
script = (ROOT / 'vps/deploy-tachyon-route-fix.ps1').read_text(encoding='utf-8')
self.script = script.split("$RemoteScript = @'\n", 1)[1].split("\n'@", 1)[0]
for old, path in (('backup=/root/owrt-remote-backup-before-tachyon-route-fix-v121', self.root / 'backup'),
('hub=/opt/owrt-remote/owrt-remote-hub.py', self.hub),
('xray_config=/etc/xray/owrt-remote.json', self.xray)):
self.script = self.script.replace(old, old.split('=', 1)[0] + '=' + shlex.quote(path.as_posix()))
self.script = self.script.replace('test -x /usr/local/bin/xray', 'true').replace('/usr/local/bin/xray -test', 'test_xray -test')
self.mocks = r'''
python3() {
if [ "$1" = -m ]; then return 0; fi
if [ "$1" = - ] && [ "$#" = 3 ]; then cat >/dev/null; printf 'new xray' >"$3"; return; fi
if [ "$1" = - ]; then cat >/dev/null; [ "${FAIL_HEALTH:-0}" = 0 ]; return; fi
printf 'new xray' >"$4"
}
test_xray() { [ "${FAIL_VALIDATION:-0}" = 0 ]; }
systemctl() { [ "${FAIL_RESTART:-0}" = 0 ]; }
'''
def run_deploy(self, action='Install', **flags):
stage = self.root / 'stage'
stage.mkdir()
(stage / 'hub.py').write_text('new hub')
script = self.script.replace('stage=/tmp/__UPLOAD_NAME__', 'stage=' + shlex.quote(stage.as_posix()))
script = script.replace('__UPLOAD_NAME__', 'test').replace('__ACTION__', action)
result = subprocess.run([SH], input=self.mocks + script, capture_output=True, text=True,
env={**self.env, **flags}, timeout=20)
self.assertFalse(stage.exists())
return result
def test_success_and_rollback_restore_both_files(self):
result = self.run_deploy()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hub.read_text(), 'new hub')
self.assertEqual(self.xray.read_text(), 'new xray')
result = self.run_deploy('Rollback')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(self.hub.read_text(), 'old hub')
self.assertEqual(self.xray.read_text(), 'old xray')
def test_invalid_xray_never_replaces_either_file(self):
result = self.run_deploy(FAIL_VALIDATION='1')
self.assertNotEqual(result.returncode, 0)
self.assertIn('validate-xray', result.stderr)
self.assertEqual(self.hub.read_text(), 'old hub')
self.assertEqual(self.xray.read_text(), 'old xray')
self.assertFalse((self.root / 'backup').exists())
def test_failed_restart_restores_current_attempt(self):
result = self.run_deploy(FAIL_RESTART='1')
self.assertNotEqual(result.returncode, 0)
self.assertIn('Restoring Hub and Xray', result.stderr)
self.assertEqual(self.hub.read_text(), 'old hub')
self.assertEqual(self.xray.read_text(), 'old xray')
def test_missing_backup_is_read_only(self):
result = self.run_deploy('Rollback')
self.assertNotEqual(result.returncode, 0)
self.assertEqual(self.hub.read_text(), 'old hub')
self.assertEqual(self.xray.read_text(), 'old xray')
def test_config_patch_preserves_vless_port_clients_and_other_services(self):
text=(ROOT/'vps/deploy-tachyon-route-fix.ps1').read_text()
code=text.split("<<'PY'\n",1)[1].split('\nPY',1)[0]
config={'inbounds':[{'tag':'vless','port':9443,'settings':{'clients':[{'id':'test-secret'}]}},
{'tag':'tachyon-main','protocol':'tunnel','listen':'127.0.0.1','port':24000,
'settings':{'allowedNetwork':'tcp','rewriteAddress':'127.0.0.1','rewritePort':1680}}],
'outbounds':[{'tag':'custom','protocol':'freedom'}], 'log':{'loglevel':'warning'}}
source=self.root/'source.json'; target=self.root/'candidate.json'
source.write_text(json.dumps(config))
result=subprocess.run([sys.executable,'-c',code,str(source),str(target)],capture_output=True,text=True)
self.assertEqual(result.returncode,0,result.stderr)
actual=json.loads(target.read_text())
self.assertEqual(actual['inbounds'][0],config['inbounds'][0])
self.assertEqual(actual['outbounds'],config['outbounds'])
settings=actual['inbounds'][1]['settings']
self.assertEqual(settings['port'],1680)
self.assertEqual(settings['address'],'127.0.0.1')
self.assertEqual(settings['network'],'tcp')
if __name__ == '__main__':
unittest.main()
+26
View File
@@ -0,0 +1,26 @@
const fs = require('node:fs');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const source = fs.readFileSync('vps/owrt-remote-hub.py', 'utf8');
const start = source.indexOf('function renderTachyon(router) {{');
const end = source.indexOf('\nfunction render(list)', start);
const code = source.slice(start, end).replaceAll('{{', '{').replaceAll('}}', '}');
const escape = value => String(value).replace(/[&<>"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[ch]));
const context = {escapeHtml: escape, escapeAttr: escape};
vm.createContext(context); vm.runInContext(code, context);
assert.equal(context.renderTachyon({}), '');
assert.equal(context.renderTachyon({tachyon: {installed: false}}), '');
const router = {permissions: {admin: true}, tachyon: {installed: true, version: '2.0.0~beta.8-1', online: true, url: '/tachyon/a/'}};
let html = context.renderTachyon(router);
assert(html.includes('Открыть Tachyon'));
assert(html.includes('target="_blank"'));
assert(html.includes('Online'));
assert(html.includes('href="/tachyon/a/"'));
router.tachyon.online = false;
assert(context.renderTachyon(router).includes('Offline'));
router.permissions.admin = false;
assert(!context.renderTachyon(router).includes('<a '));
router.permissions.admin = true; router.tachyon.version = '<img onerror=alert(1)>';
assert(!context.renderTachyon(router).includes('<img '));
assert.equal(source.split(String.fromCharCode(36) + '{{renderTachyon(r)}}').length - 1, 2);
console.log('TACHYON_UI_OK: absent, installed, offline, access controls, escaping and both layouts');
+3 -3
View File
@@ -130,9 +130,9 @@ sleep() { return 0; }
class VersionDeployTests(UpdateStatusDeployTests):
deploy_file = 'deploy-version-v121.ps1'
backup_name = 'hub.py.bak-before-v121'
success_marker = 'HUB_V121_Install_OK'
deploy_file = 'deploy-version-v122.ps1'
backup_name = 'hub.py.bak-before-v122'
success_marker = 'HUB_V122_Install_OK'
if __name__ == '__main__':
+10 -4
View File
@@ -402,11 +402,13 @@ xray_discover_releases() {
printf 'v26.6.27|missing.ipk|https://github.com/missing|%s|%s\n' "$(xray_digest "$TEST_ROOT/release.pkg")" "$(wc -c <"$TEST_ROOT/release.pkg")" >"$1"
printf 'v26.6.27|published.ipk|https://github.com/published|%s|%s\n' "$(xray_digest "$TEST_ROOT/release.pkg")" "$(wc -c <"$TEST_ROOT/release.pkg")" >>"$1"
}
xray_probe_url() { case "$1" in */missing) return 22 ;; esac; }
fetch_file() { cp "$TEST_ROOT/release.pkg" "$2"; }
fetch_file() {
case "$1" in */missing) printf '22 HTTP 404\n' >"$DOWNLOAD_RESULT_FILE"; return 22 ;; esac
cp "$TEST_ROOT/release.pkg" "$2"
}
''')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('URL unavailable (rc=22)', result.stderr)
self.assertIn('http=404', result.stderr)
self.assertEqual(self.binary.read_bytes(), data)
self.assert_clean()
@@ -544,7 +546,7 @@ curl() {
calls = (self.directory / 'fetches').read_text().splitlines()
for call, host in zip(calls, ('github.com', 'release-assets.githubusercontent.com')):
self.assertIn('--connect-timeout 10', call)
self.assertIn('--max-time 120.000', call)
self.assertRegex(call, r'--max-time [1-9][0-9]*\.000')
self.assertIn('--resolve ' + host + ':443:192.0.2.42', call)
self.assertIn('--interface wan', call)
self.assertNotIn('--insecure', call)
@@ -561,6 +563,10 @@ curl() {
def test_download_timeout_removes_partial_data_and_preserves_error(self):
result = self.shell('fetch_file https://github.com/test "$TEST_ROOT/download"', mocks=r'''
curl() { local arg previous; previous=''; for arg in "$@"; do [ "$previous" != -o ] || echo partial >"$arg"; previous="$arg"; done; return 28; }
command() {
if [ "$1" = -v ]; then case "$2" in wget|uclient-fetch) return 1 ;; esac; fi
builtin command "$@"
}
''')
self.assertEqual(result.returncode, 28, result.stderr)
self.assertFalse((self.directory / 'download').exists())
+21
View File
@@ -0,0 +1,21 @@
"""Local download-fix payload installation and rollback, no SSH required."""
import unittest
from test_xray_apk_deploy import XrayApkDeploymentTests
class XrayDownloadDeploymentTests(XrayApkDeploymentTests):
deploy_name = 'deploy-xray-download-fix.ps1'
backup_name = 'owrt-remote-backup-before-xray-download-v121'
success_marker = 'XRAY_DOWNLOAD_ROUTER_Install_OK'
def test_failed_xray_preparation_restores_agent_and_retains_backup(self):
self.env['PREPARE_RC'] = '13'
result = self.deploy('Install')
self.assertEqual(result.returncode, 13, result.stderr)
self.assertIn('prepare-xray-download', result.stderr)
self.assertEqual(self.targets['agent'].read_bytes(), self.original['agent'])
self.assertEqual(self.backup.joinpath('agent').read_bytes(), self.original['agent'])
if __name__ == '__main__':
unittest.main()
+23
View File
@@ -189,5 +189,28 @@ fetch_file() {
self.assertEqual(self.directory.joinpath('next-release-page').read_text().strip(),'2')
self.assertEqual(len(self.directory.joinpath('fetched').read_text().splitlines()),1)
def test_same_selector_matches_only_the_exact_published_target_for_apk_and_ipk(self):
architectures = ('aarch64_cortex-a53', 'aarch64_cortex-a72', 'aarch64_generic',
'arm_cortex-a7', 'arm_cortex-a7_neon-vfpv4', 'arm_cortex-a9',
'mips_24kc', 'mipsel_24kc', 'mips64', 'i386', 'x86_64')
for fmt in ('apk', 'ipk'):
assets = []
for arch in architectures:
item = self.asset(arch=arch)
if fmt == 'ipk':
name = f'openwrt-xray_26.6.22-2_{arch}.ipk'
item['browser_download_url'] = item['browser_download_url'].replace(item['name'], name)
item['name'] = name
assets.append(item)
self.manifest([self.release(assets=assets)])
for arch in architectures:
with self.subTest(format=fmt, arch=arch):
result = self.run_case('xray_discover_releases "$TEST_ROOT/candidates" "$TEST_ROOT"; cat "$TEST_ROOT/candidates"',
mocks=f'xray_package_format() {{ printf {fmt}; }}', TEST_ARCH=arch)
self.assertEqual(result.returncode, 0, result.stderr)
selected = result.stdout.strip().splitlines()
self.assertEqual(len(selected), 1, result.stdout)
self.assertIn(('-' if fmt == 'apk' else '_') + arch + '.' + fmt, selected[0])
if __name__=='__main__': unittest.main()
+36 -2
View File
@@ -67,7 +67,7 @@ class ReverseTransportTests(unittest.TestCase):
server.server_close()
thread.join(timeout=3)
def check_pair(self, server_bin, shell_client=False):
def check_pair(self, server_bin, shell_client=False, tachyon=False):
processes, streams = [], []
row = dict(id='probe', name='probe', entry_port=free_port(), ssh_entry_port=free_port(),
vps_host='127.0.0.1', vless_port=free_port(), vless_uuid=str(uuid.uuid4()),
@@ -75,6 +75,18 @@ class ReverseTransportTests(unittest.TestCase):
reverse_tag='reverse-in', ssh_reverse_tag='reverse-in-ssh',
admin_host='127.0.0.1', admin_port=self.http_server.server_port,
ssh_host='127.0.0.1', ssh_port=self.ssh_server.server_address[1])
if tachyon:
class TachyonProbe(HTTPProbe):
def do_GET(self):
data = b'TACHYON_SELECTED_ROUTER_OK'
self.send_response(200); self.send_header('Content-Length', str(len(data)))
self.end_headers(); self.wfile.write(data)
service = ThreadingHTTPServer(('127.0.0.1', 0), TachyonProbe)
thread = threading.Thread(target=service.serve_forever, daemon=True); thread.start()
self.addCleanup(self.close_server, service, thread)
row['tachyon_entry_port'] = free_port()
row['status_json'] = json.dumps({'tachyon': {'checked': True, 'installed': True,
'mode': 'standalone', 'port': service.server_port, 'available': True}})
configs = dict(server=hub.make_server_xray_config([row], listen_host='127.0.0.1',
listen_port=row['vless_port']),
client=hub.make_router_xray_config(row))
@@ -87,7 +99,8 @@ class ReverseTransportTests(unittest.TestCase):
reverse_tag=row['reverse_tag'], ssh_reverse_tag=row['ssh_reverse_tag'],
admin_host=row['admin_host'], admin_port=row['admin_port'],
ssh_host=row['ssh_host'], ssh_port=row['ssh_port'])
result = harness.run_shell('render_client_config --stdout')
injection = ('tachyon_tunnel_port() { printf ' + str(service.server_port) + '; }\n') if tachyon else ''
result = harness.run_shell(injection + 'render_client_config --stdout')
self.assertEqual(result.returncode, 0, result.stderr)
configs['client'] = json.loads(result.stdout)
finally:
@@ -127,6 +140,14 @@ class ReverseTransportTests(unittest.TestCase):
with socket.create_connection(('127.0.0.1', row['ssh_entry_port']), timeout=3) as sock:
sock.settimeout(3)
self.assertEqual(sock.recv(128), b'SSH-2.0-OWRT_TEST\r\n', logs)
if tachyon:
connection = http.client.HTTPConnection('127.0.0.1', row['tachyon_entry_port'], timeout=5)
try:
connection.request('GET', '/')
with connection.getresponse() as result:
self.assertEqual((result.status, result.read()), (200, b'TACHYON_SELECTED_ROUTER_OK'), logs)
finally:
connection.close()
finally:
for process in processes:
process.terminate()
@@ -149,6 +170,19 @@ class ReverseTransportTests(unittest.TestCase):
def test_real_router_shell_config_with_modern_server(self):
self.check_pair(Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).resolve(), shell_client=True)
@unittest.skipUnless(SH and os.environ.get('OWRT_TEST_NEW_XRAY_BIN'), 'POSIX shell and modern server required')
def test_tachyon_admin_and_ssh_share_reverse_without_cross_routing(self):
self.check_pair(Path(os.environ['OWRT_TEST_NEW_XRAY_BIN']).resolve(), shell_client=True, tachyon=True)
@unittest.skipUnless(SH and os.environ.get('OWRT_TEST_OLD_XRAY_BIN'), 'Legacy server Xray binary required')
def test_tachyon_with_26327_server_preserves_destination_port(self):
self.check_pair(Path(os.environ['OWRT_TEST_OLD_XRAY_BIN']).resolve(), shell_client=True, tachyon=True)
@unittest.skipUnless(SH and os.environ.get('OWRT_TEST_OLD_XRAY_BIN'), 'Legacy Xray binaries required')
def test_tachyon_with_26327_router_and_server(self):
self.client_bin = Path(os.environ['OWRT_TEST_OLD_XRAY_BIN']).resolve()
self.check_pair(self.client_bin, shell_client=True, tachyon=True)
if __name__ == '__main__':
unittest.main()