Fix VPS host persistence and direct WAN routing in v111
This commit is contained in:
1 parent
411f95d6ba
commit
b854d3a001
20 files changed
+2097
-49
No files matched your search
@@ -0,0 +1,145 @@
|
||||
# Фиксация VPS host и независимое соединение Remote через WAN (v111)
|
||||
|
||||
`vps_host_mode=manual` сохраняет заданный на роутере адрес. Это значение
|
||||
используется и когда опция отсутствует у старой установки. Только явно
|
||||
выбранное `auto` позволяет принять `hub_update.vps_host`. Ни один ответ
|
||||
heartbeat не может сам включить автоматический режим. Изменения и
|
||||
отклонённые предложения пишутся через `logger -t owrt-remote` в logread;
|
||||
повтор одинакового отклонённого предложения не засоряет журнал.
|
||||
|
||||
Hub сохраняет прежнее поведение для старых агентов, ещё не сообщающих
|
||||
режим. Сам обновлённый агент по умолчанию защищает ручной адрес даже
|
||||
при старой версии Hub. Для полного фикса сначала обновляется роутер.
|
||||
|
||||
На роутере в настройках есть «Автоматически обновлять VPS host».
|
||||
Блок «Настроить VPS host» убран из карточек Hub на ПК и мобильном.
|
||||
Он не появляется при периодическом обновлении карточек. Сам механизм
|
||||
ручного/автоматического режима и API применения адреса по SSH сохраняются.
|
||||
OpenWrt config / автоматическое переприменение конфигурации больше не
|
||||
удаляет всю UCI-секцию и сохраняет существующий ручной адрес и WAN-параметры.
|
||||
|
||||
## Прямой WAN
|
||||
|
||||
`wan_direct=1` включает отдельный маршрут для Remote; по умолчанию эта
|
||||
опция выключена в поставляемой конфигурации и старых установках. Скрипт
|
||||
локальной установки ниже включает её для тестирования на вашем роутере.
|
||||
|
||||
* `wan_interface=wan` — логическое имя интерфейса OpenWrt. Реальный
|
||||
`l3_device` (включая PPPoE) берётся через ubus. Он должен иметь физический
|
||||
default route в main; TUN-устройства не принимаются как WAN.
|
||||
* Таблица маршрутов `210` и приоритет `104` принадлежат Remote.
|
||||
В таблицу копируется только default route выбранного WAN.
|
||||
Номер таблицы совместим со штатным BusyBox ip. Занятые другим сервисом
|
||||
таблица или приоритет приводят к отказу до изменения маршрутов.
|
||||
* Вместо дополнительных nftables-правил используются адресные `ip rule`
|
||||
с `iif lo`. Они выбирают только пакеты, созданные самим роутером, к реальным
|
||||
адресам Hub, действующего Xray и DNS выбранного WAN. LAN/FORWARD не меняются.
|
||||
Ограничение по портам не используется: весь локальный трафик к этим адресам
|
||||
идёт через WAN. Приоритет 104 выше стандартного правила Podkop 105.
|
||||
* Только два VPS-outbound Xray получают SO_MARK `0x00200000` (штатный bypass
|
||||
Podkop) и привязку к WAN-интерфейсу. Дополнительная nft-таблица не создаётся;
|
||||
прежняя `inet owrt_remote_wan` и собственные правила `0x40000000` удаляются
|
||||
при переходе. Проверка предупреждений самого Podkop не изменяется.
|
||||
Локальные подключения к админке и SSH продолжают работать локально.
|
||||
* Для доменов используется прямой запрос к DNS провайдера на WAN
|
||||
(можно задать `wan_dns`). Ответ FakeIP 198.18.0.0/15 отклоняется.
|
||||
Успешный ответ кешируется 5 минут, при временном сбое допускается
|
||||
использование предыдущего ответа максимум час.
|
||||
* При ручном IP домен HTTPS Hub соединяется с этим IP через curl `--resolve`:
|
||||
сохраняются Host, SNI и проверка сертификата. Проверка TLS не отключается.
|
||||
Xray соединяется с IP без DNS. Запросы heartbeat ограничены по времени.
|
||||
* Правила обновляются при heartbeat и старте, очищаются при остановке/откате.
|
||||
Настройки Podkop, dnsmasq и службы sing-box не изменяются.
|
||||
|
||||
Это отделяет соединение Remote от Podkop. Общая схема fallback для клиентов
|
||||
LAN при **аварийном падении** sing-box относится к настройкам самого Podkop;
|
||||
этот фикс не обещает восстановление DNS/FakeIP-сессий всей LAN.
|
||||
|
||||
## Что известно о домене
|
||||
|
||||
08.10.2026 системный DNS на компьютере разработки возвращает для
|
||||
`owrt-zks95.developer.li` IPv4 `193.233.82.38`. Это не подтверждает, что
|
||||
роутер получает тот же ответ. В стандартном Podkop dnsmasq направляется
|
||||
на DNS sing-box. Поэтому разница «IP работает, домен периодически не
|
||||
работает» может быть вызвана DNS/FakeIP/маршрутизацией, но без логов
|
||||
самого роутера нельзя утверждать точную причину.
|
||||
|
||||
После установки команда `owrt-remote network-diagnostics` сравнивает
|
||||
системный DNS с прямым WAN DNS и показывает собственные правила Remote.
|
||||
В вывод не включаются Hub token, UUID и SSH-пароли. Для проверки поведения
|
||||
при работающем и остановленном Podkop нужен настоящий OpenWrt-роутер.
|
||||
|
||||
Источники:
|
||||
[DNS, OUTPUT и диагностика Podkop 0.7.22](https://github.com/itdoginfo/podkop/blob/0.7.22/podkop/files/usr/bin/podkop),
|
||||
[маркировка Podkop 0.7.22](https://github.com/itdoginfo/podkop/blob/0.7.22/podkop/files/usr/lib/constants.sh),
|
||||
[Xray sockopt](https://xtls.github.io/en/config/transports/sockopt.html),
|
||||
[локальные пакеты и iif lo](https://man7.org/linux/man-pages/man8/ip-rule.8.html),
|
||||
[ограничение ID таблиц в BusyBox ip](https://github.com/mirror/busybox/blob/master/networking/libiproute/rt_names.c).
|
||||
|
||||
## Установка и откат с Windows 11
|
||||
|
||||
В PowerShell из каталога проекта. При другом IP роутера или логическом
|
||||
имени WAN замените значения параметров. VPS host фиксируется на указанном IP.
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -PinnedVpsHost "193.233.82.38" -WanInterface "wan" -Action Install
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Vps -Machine "root@193.233.82.38" -Action Install
|
||||
```
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -Action Rollback
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Vps -Machine "root@193.233.82.38" -Action Rollback
|
||||
```
|
||||
|
||||
Установка загружает локальные файлы, без Git. До остановки службы проверяются
|
||||
доступность WAN и поддержка таблицы реальной командой ip на роутере.
|
||||
На роутер загружается и файл LuCI: версия v111 появляется и в основной
|
||||
CGI-панели, и в странице входа в неё через LuCI.
|
||||
Сначала сохраняются файлы
|
||||
и конфигурация; после замены проверяется heartbeat/health. При ошибке
|
||||
автоматически восстанавливается состояние перед текущей попыткой.
|
||||
Сохранённая резервная копия для ручного отката не перезаписывается.
|
||||
|
||||
* Роутер: `/root/owrt-remote-backup-before-host-policy-v111` — агент,
|
||||
helper, init, CGI, UCI-конфигурация и Xray-конфиг (в закрытом каталоге).
|
||||
* VPS: `/opt/owrt-remote/owrt-remote-hub.py.bak-before-host-policy-v111`.
|
||||
База роутеров и настройки авторизации не заменяются.
|
||||
|
||||
Успешная установка заканчивается `HOST_POLICY_ROUTER_V111_OK` на роутере
|
||||
и `HOST_POLICY_VPS_V111_Install_OK` на VPS. Старые резервные копии предыдущей
|
||||
версии сохраняются; новые команды отката используют отдельные копии для v111.
|
||||
|
||||
### Переход с nftables-маркировки на адресную маршрутизацию
|
||||
|
||||
Для уже настроенного роутера используется отдельная резервная копия.
|
||||
Эти команды сохраняют существующие VPS host, ручной/auto режим и WAN-настройки.
|
||||
Обновление VPS для этого изменения не требуется.
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -PreserveConnectionSettings -BackupName "podkop-compat-v111" -Action Install
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-host-policy.ps1" -Target Router -Machine "root@192.168.2.1" -BackupName "podkop-compat-v111" -Action Rollback
|
||||
```
|
||||
|
||||
Копия: `/root/owrt-remote-backup-before-podkop-compat-v111`.
|
||||
После установки повторите диагностику Podkop. Предупреждение от прежних правил
|
||||
Remote должно исчезнуть. Настоящие дополнительные правила других приложений
|
||||
по-прежнему обнаруживаются штатной диагностикой.
|
||||
|
||||
## Локальные проверки
|
||||
|
||||
```powershell
|
||||
python -m unittest discover -s tests -v
|
||||
python tests/test_recaptcha.py --export-js .test-output/recaptcha
|
||||
node --check .test-output/recaptcha/dashboard.js
|
||||
node tests/test_host_policy_ui.cjs .test-output/recaptcha/dashboard.js
|
||||
```
|
||||
|
||||
Shell-тесты исполняют код агента в Git for Windows sh или Linux sh
|
||||
с подменёнными UCI, ubus, DNS, nft, ip и curl. Проверяются ручной/auto режим,
|
||||
сохранение IP при rebind, реальные аргументы curl/Xray, WAN-таблицы,
|
||||
миграция прежних правил, отсутствие дубликатов при heartbeat, сохранение
|
||||
адреса работающего туннеля при смене DNS, IPv6, ошибки DNS и восстановление.
|
||||
Оригинальная функция `check_nft_rules` из Podkop 0.7.22 исполняется на подменённом
|
||||
nft: прежние правила дают предупреждение, переход убирает его, а посторонние
|
||||
маркирующие правила по-прежнему вызывают предупреждение.
|
||||
Это не заменяет аппаратную проверку nftables и Podkop на OpenWrt.
|
||||
@@ -1,4 +1,4 @@
|
||||
# reCAPTCHA v3 в OpenWrt Remote Hub v110
|
||||
# reCAPTCHA v3 в OpenWrt Remote Hub v111
|
||||
|
||||
В меню владельца, в блоке «Капча на экране входа», доступны цифры,
|
||||
Google reCAPTCHA v2 Checkbox и Google reCAPTCHA v3. Установка обновления
|
||||
@@ -74,8 +74,8 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-recaptcha-v3
|
||||
непосредственно перед попыткой. Резервные копии при повторном запуске
|
||||
не перезаписываются:
|
||||
|
||||
* `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v110`
|
||||
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v110.json` (режим 0600).
|
||||
* `/opt/owrt-remote/owrt-remote-hub.py.bak-before-recaptcha-v3-v111`
|
||||
* `/opt/owrt-remote/captcha-before-recaptcha-v3-v111.json` (режим 0600).
|
||||
|
||||
Скрипт рассчитан на стандартные пути установленного Hub:
|
||||
`/opt/owrt-remote/owrt-remote-hub.py`, `/var/lib/owrt-remote/hub-auth.json`
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Аудит ресурсов OpenWrt Remote Hub v110
|
||||
# Аудит ресурсов OpenWrt Remote Hub v111
|
||||
|
||||
Исправления внесены поверх `7f809fd`. Версия панели остаётся v110.
|
||||
Исправления внесены поверх `7f809fd`. Версия панели остаётся v111.
|
||||
|
||||
## SQLite
|
||||
|
||||
@@ -115,7 +115,7 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File "vps\deploy-resource-fix
|
||||
|
||||
Установщик загружает локальный файл без Git, запускает изолированные тесты,
|
||||
сохраняет исходный серверный файл:
|
||||
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v110`,
|
||||
`/opt/owrt-remote/owrt-remote-hub.py.bak-before-resource-fix-v111`,
|
||||
атомарно заменяет Python файл, перезапускает `owrt-remote` и проверяет health.
|
||||
Существующая резервная копия не перезаписывается. При ошибке установки
|
||||
восстанавливается файл, работавший непосредственно перед текущей попыткой.
|
||||
|
||||
Vendored
+339
@@ -0,0 +1,339 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1989
|
||||
Ty Coon, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
# Diagnostic fixture from Podkop 0.7.22 (GPL-2.0; see PODKOP-LICENSE).
|
||||
# https://github.com/itdoginfo/podkop/blob/0.7.22/podkop/files/usr/bin/podkop
|
||||
# Commit c0a2736bb95884c19fedf638345ed6148c5fd6af
|
||||
check_nft_rules() {
|
||||
local table_exist=0
|
||||
local rules_mangle_exist=0
|
||||
local rules_mangle_counters=0
|
||||
local rules_mangle_output_exist=0
|
||||
local rules_mangle_output_counters=0
|
||||
local rules_proxy_exist=0
|
||||
local rules_proxy_counters=0
|
||||
local rules_other_mark_exist=0
|
||||
|
||||
# Generate traffic through PodkopTable
|
||||
curl -m 3 -s "https://$CHECK_PROXY_IP_DOMAIN/check" > /dev/null 2>&1 &
|
||||
local pid1=$!
|
||||
curl -m 3 -s "https://$FAKEIP_TEST_DOMAIN/check" > /dev/null 2>&1 &
|
||||
local pid2=$!
|
||||
|
||||
wait $pid1 2> /dev/null
|
||||
wait $pid2 2> /dev/null
|
||||
sleep 1
|
||||
|
||||
# Check if PodkopTable exists
|
||||
if nft list table inet "$NFT_TABLE_NAME" > /dev/null 2>&1; then
|
||||
table_exist=1
|
||||
|
||||
# Check mangle chain rules
|
||||
if nft list chain inet "$NFT_TABLE_NAME" mangle > /dev/null 2>&1; then
|
||||
local mangle_output
|
||||
mangle_output=$(nft list chain inet "$NFT_TABLE_NAME" mangle)
|
||||
if echo "$mangle_output" | grep -q "counter"; then
|
||||
rules_mangle_exist=1
|
||||
|
||||
if echo "$mangle_output" | grep "counter" | grep -qv "packets 0 bytes 0"; then
|
||||
rules_mangle_counters=1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check mangle_output chain rules
|
||||
if nft list chain inet "$NFT_TABLE_NAME" mangle_output > /dev/null 2>&1; then
|
||||
local mangle_output_output
|
||||
mangle_output_output=$(nft list chain inet "$NFT_TABLE_NAME" mangle_output)
|
||||
if echo "$mangle_output_output" | grep -q "counter"; then
|
||||
rules_mangle_output_exist=1
|
||||
|
||||
if echo "$mangle_output_output" | grep "counter" | grep -qv "packets 0 bytes 0"; then
|
||||
rules_mangle_output_counters=1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check proxy chain rules
|
||||
if nft list chain inet "$NFT_TABLE_NAME" proxy > /dev/null 2>&1; then
|
||||
local proxy_output
|
||||
proxy_output=$(nft list chain inet "$NFT_TABLE_NAME" proxy)
|
||||
if echo "$proxy_output" | grep -q "counter"; then
|
||||
rules_proxy_exist=1
|
||||
|
||||
if echo "$proxy_output" | grep "counter" | grep -qv "packets 0 bytes 0"; then
|
||||
rules_proxy_counters=1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check for other mark rules outside PodkopTable
|
||||
nft list tables 2> /dev/null | while read -r _ family table_name; do
|
||||
[ -z "$table_name" ] && continue
|
||||
|
||||
[ "$table_name" = "$NFT_TABLE_NAME" ] && continue
|
||||
|
||||
if nft list table "$family" "$table_name" 2> /dev/null | grep -q "meta mark set"; then
|
||||
touch /tmp/podkop_mark_check.$$
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -f /tmp/podkop_mark_check.$$ ]; then
|
||||
rules_other_mark_exist=1
|
||||
rm -f /tmp/podkop_mark_check.$$
|
||||
fi
|
||||
|
||||
echo "{\"table_exist\":$table_exist,\"rules_mangle_exist\":$rules_mangle_exist,\"rules_mangle_counters\":$rules_mangle_counters,\"rules_mangle_output_exist\":$rules_mangle_output_exist,\"rules_mangle_output_counters\":$rules_mangle_output_counters,\"rules_proxy_exist\":$rules_proxy_exist,\"rules_proxy_counters\":$rules_proxy_counters,\"rules_other_mark_exist\":$rules_other_mark_exist}" | jq .
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
"""Host locking and WAN isolation regressions; no router/network is required."""
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SOURCE = Path(os.environ.get("OWRT_HOST_POLICY_HUB_SOURCE", ROOT / "vps/owrt-remote-hub.py"))
|
||||
STATE = tempfile.TemporaryDirectory(prefix="owrt-host-policy-tests-")
|
||||
spec = importlib.util.spec_from_file_location("host_policy_hub", SOURCE)
|
||||
hub = importlib.util.module_from_spec(spec)
|
||||
sys.modules[spec.name] = hub
|
||||
with mock.patch.dict(os.environ, {"OWRT_REMOTE_STATE_DIR": STATE.name}):
|
||||
spec.loader.exec_module(hub)
|
||||
|
||||
SH = shutil.which("sh")
|
||||
if not SH and os.name == "nt":
|
||||
candidate = Path(os.environ.get("ProgramFiles", "C:/Program Files")) / "Git/usr/bin/sh.exe"
|
||||
SH = str(candidate) if candidate.exists() else None
|
||||
|
||||
MOCKS = r'''
|
||||
uci() {
|
||||
[ "$1" != -q ] || shift
|
||||
case "$1" in
|
||||
get)
|
||||
if [ "$2" = owrtremote.main ]; then echo remote; return; fi
|
||||
awk -F= -v key="$2" '$1==key { sub(/^[^=]*=/, ""); print; found=1; exit } END { if (!found) exit 1 }' "$TEST_ROOT/uci"
|
||||
;;
|
||||
set)
|
||||
key="${2%%=*}"; value="${2#*=}"
|
||||
awk -F= -v key="$key" '$1!=key' "$TEST_ROOT/uci" >"$TEST_ROOT/uci.new"
|
||||
printf '%s=%s\n' "$key" "$value" >>"$TEST_ROOT/uci.new"
|
||||
mv "$TEST_ROOT/uci.new" "$TEST_ROOT/uci"
|
||||
;;
|
||||
commit) echo commit >>"$TEST_ROOT/commits" ;;
|
||||
delete) return 0 ;;
|
||||
esac
|
||||
}
|
||||
logger() { printf '%s\n' "$*" >>"$TEST_ROOT/log"; }
|
||||
owrt-remote() {
|
||||
[ "$1" != status ] || { printf 'vps_host_mode: manual\n'; return; }
|
||||
[ "$1" != render-client ] || [ "${RENDER_FAIL:-0}" = 0 ]
|
||||
}
|
||||
ubus() { printf '{}'; }
|
||||
jsonfilter() {
|
||||
if [ "$1" = -i ]; then
|
||||
"$TEST_PYTHON" -c 'import json, re, sys; data=json.load(open(sys.argv[1])); tag=re.search(r"tag=\"([^\"]+)\"", sys.argv[2]).group(1); print(next((o.get("settings", {}).get("address", "") for o in data.get("outbounds", []) if o.get("tag")==tag), ""))' "$2" "$4"
|
||||
return
|
||||
fi
|
||||
cat >/dev/null
|
||||
case "$2" in '@.l3_device') printf pppoe-wan ;; *) printf 1.1.1.1 ;; esac
|
||||
}
|
||||
ip() {
|
||||
local previous arg family action rule address mark priority table
|
||||
printf '%s\n' "$*" >>"$TEST_ROOT/ip"
|
||||
# BusyBox's table parser rejects large IDs (older builds even above 255).
|
||||
previous=''
|
||||
for arg in "$@"; do
|
||||
if [ "$previous" = table ] && [ "$arg" -eq "$arg" ] 2>/dev/null && [ "$arg" -gt 255 ]; then
|
||||
printf "ip: invalid argument '%s' to 'table'\n" "$arg" >&2; return 1
|
||||
fi
|
||||
previous="$arg"
|
||||
done
|
||||
family="${1#-}"
|
||||
if [ "$2" = rule ]; then
|
||||
[ "$family" != 6 ] || [ "${IPV6_DISABLED:-0}" = 0 ] || return 1
|
||||
touch "$TEST_ROOT/rules-$family"
|
||||
action="$3"
|
||||
if [ "$action" = show ]; then
|
||||
cat "$TEST_ROOT/rules-$family"
|
||||
elif [ "$action" = add ] || [ "$action" = del ]; then
|
||||
shift 3
|
||||
address=''; mark=''; priority=''; table=''
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
priority) priority="$2" ;;
|
||||
to) address="$2" ;;
|
||||
fwmark) mark="$2" ;;
|
||||
table) table="$2" ;;
|
||||
iif) [ "$2" = lo ] || return 1 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
shift 2
|
||||
done
|
||||
if [ -n "$address" ]; then
|
||||
# ip normalizes IPv6 spelling in the actual kernel's rule dump.
|
||||
case "$address" in *:*) address="$("$TEST_PYTHON" -c 'import ipaddress,sys; print(ipaddress.ip_interface(sys.argv[1]).ip.compressed)' "$address")" ;; esac
|
||||
rule="$priority: from all to $address iif lo lookup $table"
|
||||
else
|
||||
rule="$priority: from all fwmark $mark lookup $table"
|
||||
fi
|
||||
if [ "$action" = add ]; then
|
||||
[ "${RULE_ADD_FAIL:-}" != "$address" ] || return 1
|
||||
printf '%s\n' "$rule" >>"$TEST_ROOT/rules-$family"
|
||||
else
|
||||
awk -v rule="$rule" '$0==rule { found=1; next } { print } END { if(!found) exit 1 }' "$TEST_ROOT/rules-$family" >"$TEST_ROOT/rules-new-$family" || return 1
|
||||
mv "$TEST_ROOT/rules-new-$family" "$TEST_ROOT/rules-$family"
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
case "$*" in
|
||||
'-6 rule show') [ "${IPV6_DISABLED:-0}" = 0 ] || return 1 ;;
|
||||
'-4 route show table main default dev pppoe-wan')
|
||||
[ "${WAN_DOWN:-0}" = 0 ] && echo 'default via 10.0.0.1 dev pppoe-wan' ;;
|
||||
'-4 rule show')
|
||||
case "${TABLE_CONFLICT:-}" in
|
||||
rule) echo '105: from all fwmark 0x10000 lookup 210' ;;
|
||||
priority) echo '104: from all fwmark 0x10000 lookup 105' ;;
|
||||
esac ;;
|
||||
'-4 route show table 210')
|
||||
if [ "${TABLE_MISSING:-0}" = 1 ]; then echo 'Error: ipv4: FIB table does not exist.' >&2; return 2; fi
|
||||
[ "${TABLE_CONFLICT:-}" != route ] || echo 'default via 192.0.2.1 dev other-wan' ;;
|
||||
esac
|
||||
return 0
|
||||
}
|
||||
nft() {
|
||||
printf '%s\n' "$*" >>"$TEST_ROOT/nft"
|
||||
case "$*" in
|
||||
'list tables')
|
||||
printf 'table inet PodkopTable\n'
|
||||
[ ! -f "$TEST_ROOT/legacy-nft" ] || printf 'table inet owrt_remote_wan\n'
|
||||
[ ! -f "$TEST_ROOT/foreign-nft" ] || printf 'table inet vpn_other\n'
|
||||
return 0 ;;
|
||||
'list table inet PodkopTable') printf 'meta mark set 0x00100000\n'; return 0 ;;
|
||||
'list chain inet PodkopTable '*) printf 'counter packets 12 bytes 1200\n'; return 0 ;;
|
||||
'list table inet owrt_remote_wan') test -f "$TEST_ROOT/legacy-nft" && cat "$TEST_ROOT/legacy-nft" ;;
|
||||
'list table inet vpn_other') test -f "$TEST_ROOT/foreign-nft" && cat "$TEST_ROOT/foreign-nft" ;;
|
||||
'delete table inet owrt_remote_wan')
|
||||
[ "${NFT_FAIL:-0}" = 0 ] || return 1
|
||||
rm -f "$TEST_ROOT/legacy-nft" ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
nslookup() {
|
||||
printf '%s\n' "$*" >>"$TEST_ROOT/dns"
|
||||
[ "${DNS_FAIL:-0}" = 0 ] || return 1
|
||||
printf 'Server: 1.1.1.1\nAddress: 1.1.1.1:53\n\nName: hub.example\nAddress 1: %s\n' "${DNS_ANSWER:-193.233.82.38}"
|
||||
}
|
||||
curl() { printf '<%s>\n' "$@" >"$TEST_ROOT/curl"; }
|
||||
'''
|
||||
|
||||
|
||||
class HostPolicyTests(unittest.TestCase):
|
||||
def row(self, mode="manual", host="193.233.82.38"):
|
||||
return {"id": "test-router", "vps_host": "hub.example", "public_url": "https://hub.example", "status_json": json.dumps({"vps_host_mode": mode, "vps_host": host})}
|
||||
|
||||
def test_manual_heartbeat_never_proposes_a_new_tunnel_host(self):
|
||||
for row in (self.row(), {"vps_host": "hub.example", "status": {"vps_host_mode": "manual"}}):
|
||||
update = hub.canonical_router_hub_update(row, "https://hub.example")
|
||||
self.assertNotIn("vps_host", update)
|
||||
self.assertEqual(update["hub_url"], "https://hub.example")
|
||||
|
||||
def test_legacy_agent_keeps_central_update_until_policy_reported(self):
|
||||
self.assertEqual(hub.canonical_router_hub_update({"vps_host": "hub.example"})["vps_host"], "hub.example")
|
||||
|
||||
def test_new_config_explicitly_defaults_to_manual(self):
|
||||
payload = hub.build_openwrt_config_payload({"id": "new", "vps_host": "193.233.82.38"}, "https://hub.example")
|
||||
self.assertEqual(payload["vps_host_mode"], "manual")
|
||||
|
||||
def test_auto_heartbeat_retains_central_host(self):
|
||||
self.assertEqual(hub.canonical_router_hub_update(self.row("auto"))["vps_host"], "hub.example")
|
||||
|
||||
def test_rebind_prefers_manual_reported_ip_over_public_hostname(self):
|
||||
bundle, url, host = hub.router_current_hub_bundle(self.row(), "https://hub.example")
|
||||
self.assertEqual(host, "193.233.82.38")
|
||||
self.assertEqual(url, "https://hub.example")
|
||||
self.assertEqual(bundle["vps_host"], host)
|
||||
|
||||
def test_mode_reads_row_and_api_status_and_handles_invalid_json(self):
|
||||
for status in ("not-json", "[]", "null"):
|
||||
self.assertEqual(hub.router_reported_connection({"status_json": status, "vps_host": "193.233.82.38"}), ("auto", "193.233.82.38"))
|
||||
self.assertEqual(hub.router_reported_connection({"status": {"vps_host_mode": "auto", "vps_host": "hub.example"}}), ("auto", "hub.example"))
|
||||
|
||||
def test_ui_script_validates_before_ssh_and_checks_agent_version(self):
|
||||
for host in ("", "https://hub.example", "host:8443", "x'; reboot", "bad..domain", "-bad.host", "999.999.999.999"):
|
||||
with self.assertRaises(ValueError):
|
||||
hub.make_router_vps_host_script(host, "manual")
|
||||
with self.assertRaises(ValueError):
|
||||
hub.make_router_vps_host_script("193.233.82.38", "invalid")
|
||||
self.assertIn("Сначала обнови агент", hub.make_router_vps_host_script("193.233.82.38", "manual"))
|
||||
|
||||
def test_hub_ui_endpoint_requires_owner_and_only_saves_after_remote_ack(self):
|
||||
from types import SimpleNamespace
|
||||
db = Path(STATE.name) / "policy-api.db"
|
||||
with hub.connect(db) as conn:
|
||||
hub.init_db(conn)
|
||||
hub.upsert_router(conn, {"id": "test", "vps_host": "old.example"})
|
||||
handler = object.__new__(hub.Handler)
|
||||
handler.server = SimpleNamespace(app=SimpleNamespace(conn=lambda: hub.connect(db)))
|
||||
handler.parsed = lambda: SimpleNamespace(path="/api/router/test/vps-host")
|
||||
handler.maybe_proxy_luci_absolute = lambda path: False
|
||||
handler.require_admin = lambda: True
|
||||
handler.send_json = mock.Mock()
|
||||
handler.run_router_ssh_script = mock.Mock(return_value="VPS_HOST_APPLIED\n")
|
||||
handler.read_payload = mock.Mock(return_value={"vps_host": "193.233.82.38", "vps_host_mode": "manual", "ssh_password": "test-password"})
|
||||
handler.require_owner = lambda **kwargs: False
|
||||
handler.do_POST()
|
||||
handler.read_payload.assert_not_called()
|
||||
handler.run_router_ssh_script.assert_not_called()
|
||||
handler.require_owner = lambda **kwargs: True
|
||||
handler.run_router_ssh_script.side_effect = RuntimeError("SSH failed")
|
||||
handler.do_POST()
|
||||
with hub.connect(db) as conn:
|
||||
self.assertEqual(hub.get_router(conn, "test")["vps_host"], "old.example")
|
||||
self.assertEqual(handler.send_json.call_args.args[0], 400)
|
||||
handler.run_router_ssh_script.side_effect = None
|
||||
handler.do_POST()
|
||||
self.assertEqual(handler.send_json.call_args.args[0], 200)
|
||||
with hub.connect(db) as conn:
|
||||
row = hub.get_router(conn, "test")
|
||||
self.assertEqual(row["vps_host"], "193.233.82.38")
|
||||
self.assertEqual(hub.router_reported_connection(row), ("manual", "193.233.82.38"))
|
||||
|
||||
|
||||
@unittest.skipUnless(SH, "a POSIX shell (Git for Windows or Linux) is required")
|
||||
class RouterShellTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory(prefix="owrt-shell-tests-")
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.directory = Path(self.temp.name)
|
||||
(self.directory / "uci").write_text("", encoding="utf-8")
|
||||
self.agent = (ROOT / "files/usr/sbin/owrt-remote").read_text(encoding="utf-8").split('cmd="${1:-help}"')[0]
|
||||
self.env = {**os.environ, "TEST_ROOT": self.directory.as_posix(), "TMPDIR": self.directory.as_posix(), "TEST_PYTHON": Path(sys.executable).as_posix(), "OWRT_REMOTE_WAN_HELPER": (ROOT / "files/usr/lib/owrt-remote/wan.sh").as_posix()}
|
||||
|
||||
def config(self, **kwargs):
|
||||
(self.directory / "uci").write_text("".join(f"owrtremote.main.{key}={value}\n" for key, value in kwargs.items()), encoding="utf-8")
|
||||
|
||||
def run_shell(self, commands, **env):
|
||||
return subprocess.run([SH], input=self.agent + "\n" + MOCKS + "\n" + commands, encoding="utf-8", capture_output=True, env={**self.env, **env}, cwd=ROOT, timeout=30)
|
||||
|
||||
def test_old_and_explicit_manual_modes_ignore_host_rewrite(self):
|
||||
response = {"hub_update": {"vps_host": "hub.example", "hub_url": "https://hub.example", "public_url": "https://hub.example"}}
|
||||
(self.directory / "response").write_text(json.dumps(response), encoding="utf-8")
|
||||
for mode in (None, "manual", "invalid"):
|
||||
values = {"vps_host": "193.233.82.38", "hub_url": "https://hub.example", "public_url": "https://hub.example"}
|
||||
if mode: values["vps_host_mode"] = mode
|
||||
self.config(**values)
|
||||
result = self.run_shell('heartbeat_apply_hub_update "$TEST_ROOT/response" https://hub.example; uci_get vps_host ""')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "193.233.82.38")
|
||||
self.assertIn("reason=manual", (self.directory / "log").read_text(encoding="utf-8"))
|
||||
|
||||
def test_explicit_auto_changes_host_and_logs_old_new_reason(self):
|
||||
self.config(vps_host="193.233.82.38", vps_host_mode="auto")
|
||||
(self.directory / "response").write_text(json.dumps({"hub_update": {"vps_host": "hub.example"}}), encoding="utf-8")
|
||||
result = self.run_shell('heartbeat_apply_hub_update "$TEST_ROOT/response" https://hub.example; uci_get vps_host ""')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "hub.example")
|
||||
self.assertIn("old=193.233.82.38 new=hub.example reason=hub_update mode=auto", result.stderr)
|
||||
|
||||
def test_hub_generated_rebind_preserves_manual_ip_and_wan_options(self):
|
||||
self.config(vps_host="193.233.82.38", wan_direct="1", wan_dns="9.9.9.9", wan_interface="internet")
|
||||
payload = hub.build_openwrt_config_payload(self.row(), "https://hub.example")
|
||||
script = "\n".join(hub.build_openwrt_config_lines(payload, mode="ssh-apply"))
|
||||
result = self.run_shell(script + '\nprintf "host=%s wan=%s dns=%s iface=%s" "$(uci_get vps_host "")" "$(uci_get wan_direct "")" "$(uci_get wan_dns "")" "$(uci_get wan_interface "")"')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("host=193.233.82.38 wan=1 dns=9.9.9.9 iface=internet", result.stdout)
|
||||
|
||||
def row(self):
|
||||
return {"id": "test-router", "name": "test", "vps_host": "hub.example", "reverse_tag": "test-in"}
|
||||
|
||||
def test_wan_routes_only_local_hub_and_dns_without_nft_marking(self):
|
||||
self.config(vps_host="193.233.82.38", hub_url="https://hub.example", vps_host_mode="manual")
|
||||
result = self.run_shell("wan_prepare")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
rules = (self.directory / "rules-4").read_text().splitlines()
|
||||
self.assertEqual(set(rules), {"104: from all to 193.233.82.38 iif lo lookup 210", "104: from all to 1.1.1.1 iif lo lookup 210"})
|
||||
self.assertTrue(all(" iif lo " in rule for rule in rules), "forwarded br-lan traffic must not match")
|
||||
self.assertNotIn("mark set", (self.directory / "nft").read_text())
|
||||
routes = (self.directory / "ip").read_text()
|
||||
self.assertIn("via 10.0.0.1 dev pppoe-wan onlink table 210", routes)
|
||||
self.assertIn("priority 104 iif lo to 193.233.82.38 table 210", routes)
|
||||
self.assertIn("unreachable default metric 42760 table 210", routes)
|
||||
self.assertFalse((self.directory / "dns").exists(), "an IP pin does not need DNS")
|
||||
|
||||
def test_busybox_large_table_failure_is_detected_before_route_mutation(self):
|
||||
self.config(vps_host="193.233.82.38")
|
||||
result = self.run_shell("WAN_TABLE=20110; wan_preflight")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("invalid argument '20110' to 'table'", result.stderr)
|
||||
self.assertNotIn("route replace", (self.directory / "ip").read_text())
|
||||
self.assertFalse((self.directory / "nft").exists())
|
||||
result = self.run_shell("wan_prepare")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_foreign_table_or_priority_is_preserved_on_failure_and_cleanup(self):
|
||||
self.config(vps_host="193.233.82.38")
|
||||
for conflict in ("rule", "priority", "route"):
|
||||
result = self.run_shell("wan_prepare", TABLE_CONFLICT=conflict)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("WAN IPv4 table 210", result.stderr)
|
||||
self.assertNotIn("route replace", (self.directory / "ip").read_text())
|
||||
nft_log = self.directory / "nft"
|
||||
self.assertNotIn("-f", nft_log.read_text() if nft_log.exists() else "")
|
||||
result = self.run_shell("wan_cleanup", TABLE_CONFLICT=conflict)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertNotIn("route flush", (self.directory / "ip").read_text())
|
||||
|
||||
def test_cleanup_removes_routes_owned_during_partial_prepare_failure(self):
|
||||
self.config(vps_host="193.233.82.38")
|
||||
(self.directory / "legacy-nft").write_text("meta mark set 0x40000000\n")
|
||||
result = self.run_shell("wan_prepare", NFT_FAIL="1")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
result = self.run_shell("wan_cleanup")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
routes = (self.directory / "ip").read_text()
|
||||
self.assertIn("-4 route flush table 210", routes)
|
||||
self.assertIn("-6 route flush table 210", routes)
|
||||
self.assertFalse((self.directory / "owrt-remote-wan/route-owner-4").exists())
|
||||
|
||||
def test_cleanup_preserves_foreign_rule_with_different_mark_mask(self):
|
||||
self.config(vps_host="193.233.82.38")
|
||||
foreign = "104: from all fwmark 0x40000000/0x40000000 lookup 210\n"
|
||||
(self.directory / "rules-4").write_text(foreign)
|
||||
result = self.run_shell("wan_prepare")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
result = self.run_shell("wan_cleanup")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.directory / "rules-4").read_text(), foreign)
|
||||
log = (self.directory / "ip").read_text()
|
||||
self.assertNotIn("rule del", log)
|
||||
self.assertNotIn("route flush", log)
|
||||
|
||||
def test_ipv4_prepares_with_disabled_ipv6_and_missing_iproute2_table(self):
|
||||
self.config(vps_host="193.233.82.38")
|
||||
result = self.run_shell("wan_prepare", IPV6_DISABLED="1", TABLE_MISSING="1")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
routes = (self.directory / "ip").read_text()
|
||||
self.assertIn("-4 route replace default", routes)
|
||||
self.assertNotIn("-6 route replace", routes)
|
||||
|
||||
def test_curl_preserves_https_hostname_and_uses_pinned_ip(self):
|
||||
self.config(vps_host="193.233.82.38", vps_host_mode="manual")
|
||||
result = self.run_shell('wan_prepare && wan_post_json https://hub.example/api/heartbeat test-token "$TEST_ROOT/payload"')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
args = (self.directory / "curl").read_text()
|
||||
self.assertIn("<hub.example:443:193.233.82.38>", args)
|
||||
self.assertIn("<pppoe-wan>", args)
|
||||
self.assertIn("<https://hub.example/api/heartbeat>", args)
|
||||
self.assertNotIn("<-k>", args)
|
||||
self.assertIn("<--max-time>\n<10>", args)
|
||||
|
||||
def test_literal_ip_fallback_is_not_rewritten_to_a_different_pin(self):
|
||||
self.config(vps_host="193.233.82.38", vps_host_mode="manual")
|
||||
result = self.run_shell('wan_endpoint_ip http://192.0.2.5:8088/api/heartbeat')
|
||||
self.assertEqual(result.stdout, "192.0.2.5")
|
||||
|
||||
def test_wan_refresh_does_not_accumulate_policy_rules(self):
|
||||
self.config(vps_host="193.233.82.38", hub_url="https://hub.example")
|
||||
result = self.run_shell('wan_prepare && wan_prepare && wan_prepare')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.directory / "ip").read_text().count("rule add"), 2)
|
||||
|
||||
def test_migration_passes_original_podkop_diagnostic_and_keeps_foreign_warnings(self):
|
||||
self.config(vps_host="193.233.82.38", wan_direct="1")
|
||||
legacy = self.directory / "legacy-nft"
|
||||
legacy.write_text("meta mark set 0x40000000\n")
|
||||
(self.directory / "rules-4").write_text("104: from all fwmark 0x40000000 lookup 210\n105: from all fwmark 0x100000/0x100000 lookup podkop\n")
|
||||
# Execute upstream's unmodified diagnostic logic; only isolate its temp path.
|
||||
diagnostic = (ROOT / "tests/fixtures/podkop-0.7.22-check-nft.sh").read_text().replace("/tmp/podkop_mark_check", '"$TEST_ROOT"/podkop_mark_check')
|
||||
setup = diagnostic + '\nNFT_TABLE_NAME=PodkopTable; jq() { cat; }; sleep() { :; }\n'
|
||||
result = self.run_shell(setup + 'check_nft_rules; wan_prepare || exit; check_nft_rules')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
before, after = [json.loads(line) for line in result.stdout.splitlines()]
|
||||
self.assertEqual(before["rules_other_mark_exist"], 1)
|
||||
self.assertEqual(after["rules_other_mark_exist"], 0)
|
||||
self.assertTrue(all(value == 1 for key, value in after.items() if key != "rules_other_mark_exist"))
|
||||
self.assertFalse(legacy.exists())
|
||||
rules = (self.directory / "rules-4").read_text()
|
||||
self.assertNotIn("0x40000000", rules)
|
||||
self.assertIn("105: from all fwmark 0x100000/0x100000 lookup podkop", rules)
|
||||
(self.directory / "foreign-nft").write_text("meta mark set 0x10\n")
|
||||
result = self.run_shell(setup + 'wan_prepare || exit; check_nft_rules')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(json.loads(result.stdout)["rules_other_mark_exist"], 1)
|
||||
self.assertTrue((self.directory / "foreign-nft").exists())
|
||||
|
||||
def test_changed_hub_keeps_running_xray_destination_and_prunes_stale_http_ip(self):
|
||||
config = self.directory / "xray.json"
|
||||
config.write_text(json.dumps({"outbounds": [{"tag": "vps-interconn", "settings": {"address": "193.233.82.38"}}]}))
|
||||
self.config(vps_host="192.0.2.2", public_url="https://192.0.2.3:9443", xray_config=config.as_posix())
|
||||
(self.directory / "rules-4").write_text("104: from all to 192.0.2.99 iif lo lookup 210\n")
|
||||
result = self.run_shell('wan_prepare')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
rules = (self.directory / "rules-4").read_text()
|
||||
self.assertIn("193.233.82.38 iif lo", rules)
|
||||
self.assertIn("192.0.2.2 iif lo", rules)
|
||||
self.assertIn("192.0.2.3 iif lo", rules)
|
||||
self.assertNotIn("192.0.2.99", rules)
|
||||
self.assertIn("192.0.2.3 9443", (self.directory / "owrt-remote-wan/endpoints").read_text())
|
||||
config.write_text(json.dumps({"outbounds": [{"tag": "vps-interconn", "settings": {"address": "192.0.2.2"}}]}))
|
||||
result = self.run_shell('wan_prepare && wan_cleanup')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual((self.directory / "rules-4").read_text(), "")
|
||||
|
||||
def test_ipv6_compression_does_not_duplicate_rules(self):
|
||||
self.config(vps_host="2001:0db8:0:0:0:0:0:1", wan_dns="2001:4860:4860::8888")
|
||||
result = self.run_shell('wan_prepare && wan_prepare; wan_address_key ::1; wan_address_key 2001:db8::; wan_address_key ::')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), ["0:0:0:0:0:0:0:1", "2001:db8:0:0:0:0:0:0", "0:0:0:0:0:0:0:0"])
|
||||
rules = (self.directory / "rules-6").read_text().splitlines()
|
||||
self.assertEqual(len(rules), 2)
|
||||
self.assertEqual((self.directory / "ip").read_text().count("rule add"), 2)
|
||||
|
||||
def test_failed_replacement_retains_previous_direct_destination(self):
|
||||
self.config(vps_host="192.0.2.2")
|
||||
(self.directory / "rules-4").write_text("104: from all to 192.0.2.1 iif lo lookup 210\n")
|
||||
result = self.run_shell('wan_prepare', RULE_ADD_FAIL="192.0.2.2")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("192.0.2.1 iif lo", (self.directory / "rules-4").read_text())
|
||||
self.assertFalse((self.directory / "owrt-remote-wan/lock").exists())
|
||||
|
||||
def test_dns_failure_does_not_fall_back_to_system_resolver(self):
|
||||
self.config(vps_host="hub.example")
|
||||
result = self.run_shell('wan_resolve_host hub.example', DNS_FAIL="1")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual((self.directory / "dns").read_text().count("nslookup"), 0)
|
||||
self.assertIn("hub.example 1.1.1.1", (self.directory / "dns").read_text())
|
||||
|
||||
def test_wan_dns_ignores_local_fakeip_and_uses_uplink_resolver(self):
|
||||
self.config(vps_host="hub.example", wan_dns="9.9.9.9")
|
||||
result = self.run_shell('wan_prepare; wan_resolve_host hub.example')
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "193.233.82.38")
|
||||
self.assertIn("hub.example 9.9.9.9", (self.directory / "dns").read_text())
|
||||
result = self.run_shell('rm -f "$WAN_STATE"/resolve-*; wan_resolve_host hub.example', DNS_ANSWER="198.18.1.5")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
|
||||
def test_wan_prepare_fails_without_wan_and_releases_lock_on_failure(self):
|
||||
self.config(vps_host="193.233.82.38")
|
||||
(self.directory / "legacy-nft").write_text("meta mark set 0x40000000\n")
|
||||
for env in ({"WAN_DOWN": "1"}, {"NFT_FAIL": "1"}):
|
||||
result = self.run_shell("wan_prepare", **env)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse((self.directory / "owrt-remote-wan/lock").exists())
|
||||
|
||||
def test_xray_only_reverse_sockets_are_bound_to_wan(self):
|
||||
self.config(vps_host="193.233.82.38", wan_direct="1", vless_uuid="test-uuid")
|
||||
result = self.run_shell("render_client_config --stdout")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
config = json.loads(result.stdout)
|
||||
for outbound in config["outbounds"]:
|
||||
if outbound["tag"].startswith("vps-"):
|
||||
self.assertEqual(outbound["streamSettings"]["sockopt"], {"mark": 2097152, "interface": "pppoe-wan"})
|
||||
self.assertEqual(outbound["settings"]["address"], "193.233.82.38")
|
||||
else:
|
||||
self.assertNotIn("streamSettings", outbound)
|
||||
|
||||
def test_hub_ui_change_restores_previous_host_if_render_fails(self):
|
||||
self.config(vps_host="193.233.82.38", vps_host_mode="manual")
|
||||
result = self.run_shell(hub.make_router_vps_host_script("hub.example", "auto"), RENDER_FAIL="1")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
config = (self.directory / "uci").read_text()
|
||||
self.assertIn("vps_host=193.233.82.38", config)
|
||||
self.assertIn("vps_host_mode=manual", config)
|
||||
|
||||
def test_cgi_saves_manual_auto_and_wan_flags_without_exposing_secrets(self):
|
||||
cgi = (ROOT / "files/www/cgi-bin/owrt-remote").read_text(encoding="utf-8").split('\nread_request\n')[0]
|
||||
self.config(vps_host="193.233.82.38", vps_host_mode="auto")
|
||||
commands = cgi + '''
|
||||
param() {
|
||||
case "$1" in
|
||||
vps_host) echo 193.233.82.38 ;;
|
||||
wan_interface) echo wan ;;
|
||||
*) printf '' ;;
|
||||
esac
|
||||
}
|
||||
has_param() { [ "$1" = wan_direct ]; }
|
||||
save_config
|
||||
printf '%s %s' "$(uci_get vps_host_mode '')" "$(uci_get wan_direct '')"
|
||||
has_param() { [ "$1" = vps_host_auto ]; }
|
||||
save_config
|
||||
printf ' %s %s' "$(uci_get vps_host_mode '')" "$(uci_get wan_direct '')"
|
||||
'''
|
||||
result = self.run_shell(commands)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout, "manual 1 auto 0")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,96 @@
|
||||
// Run after: python tests/test_recaptcha.py --export-js .test-output/recaptcha
|
||||
// node tests/test_host_policy_ui.cjs .test-output/recaptcha/dashboard.js
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const source = fs.readFileSync(process.argv[2], 'utf8').replace(/\r\n/g, '\n');
|
||||
const begin = source.indexOf('const vpsHostDrafts = new Map();');
|
||||
const end = source.indexOf('\nfunction renderRouterNotesPanel(', begin);
|
||||
const handlersBegin = source.indexOf("cards.addEventListener('input', (ev) => {\n const field = ev.target.closest('[data-vps-field]');");
|
||||
const handlersEnd = source.indexOf("\ncards.addEventListener('click', async (ev) => {\n const pickerToggle", handlersBegin);
|
||||
assert(begin >= 0 && end > begin && handlersBegin > 0 && handlersEnd > handlersBegin);
|
||||
const handlers = {};
|
||||
let renders = 0, request;
|
||||
const router = {id: 'test', online: true, permissions: {owner: true}, status: {vps_host: '193.233.82.38', vps_host_mode: 'manual'}};
|
||||
const context = {
|
||||
escapeHtml: value => String(value).replace(/[<>&"']/g, ch => ({'<':'<', '>':'>', '&':'&', '"':'"', "'":'''}[ch])),
|
||||
escapeAttr: value => String(value).replace(/"/g, '"'),
|
||||
cards: {addEventListener(kind, handler) { handlers[kind] = handler; }},
|
||||
selectedRouter() { return router; },
|
||||
requestRouterRender() { renders++; },
|
||||
replaceRouterInList(next) { Object.assign(router, next); },
|
||||
async fetch(url, options) {
|
||||
request = {url, payload: JSON.parse(options.body)};
|
||||
return {ok: true, async json() { return {ok: true, router: {...router, status: {vps_host: request.payload.vps_host, vps_host_mode: request.payload.vps_host_mode}}}; }};
|
||||
},
|
||||
};
|
||||
vm.createContext(context);
|
||||
vm.runInContext(source.slice(begin, end) + '\n' + source.slice(handlersBegin, handlersEnd), context);
|
||||
const eventFor = (selector, node) => ({target: {closest(wanted) { return wanted === selector ? node : null; }}});
|
||||
(async () => {
|
||||
assert.equal(context.renderVpsHostSettings({...router, permissions: {manage: true}}), '', 'owner permission is required');
|
||||
const state = context.getVpsHostDraft(router);
|
||||
await handlers.click(eventFor('[data-vps-toggle]', {dataset: {vpsToggle: 'test'}}));
|
||||
assert.equal(state.open, true);
|
||||
handlers.input(eventFor('[data-vps-field]', {dataset: {vpsRouter: 'test', vpsField: 'host'}, type: 'text', value: '192.0.2.8'}));
|
||||
handlers.input(eventFor('[data-vps-field]', {dataset: {vpsRouter: 'test', vpsField: 'auto'}, type: 'checkbox', checked: true}));
|
||||
handlers.input(eventFor('[data-vps-field]', {dataset: {vpsRouter: 'test', vpsField: 'password'}, type: 'password', value: 'test-password'}));
|
||||
context.renderVpsHostSettings(router); // simulate polling refresh
|
||||
assert.equal(state.host, '192.0.2.8');
|
||||
assert.equal(state.auto, true);
|
||||
assert.equal(state.open, true);
|
||||
await handlers.click(eventFor('[data-vps-save]', {dataset: {vpsSave: 'test'}}));
|
||||
assert.equal(request.url, '/api/router/test/vps-host');
|
||||
assert.equal(request.payload.vps_host_mode, 'auto');
|
||||
assert.equal(request.payload.vps_host, '192.0.2.8');
|
||||
assert.equal(state.password, '');
|
||||
assert.equal(state.dirty, false);
|
||||
assert.equal(state.saving, false);
|
||||
context.fetch = async () => ({ok: false, async json() { return {error: 'SSH failed'}; }});
|
||||
state.dirty = true;
|
||||
state.password = 'test-password';
|
||||
await handlers.click(eventFor('[data-vps-save]', {dataset: {vpsSave: 'test'}}));
|
||||
assert.equal(state.message, 'SSH failed');
|
||||
assert.equal(state.dirty, true);
|
||||
assert.equal(state.password, '');
|
||||
assert.equal(state.saving, false);
|
||||
assert(renders > 0);
|
||||
console.log('HOST_POLICY_UI_OK: owner access, draft persistence, explicit apply, remote failure and password clearing');
|
||||
|
||||
// Exercise the active card renderer: hidden controls must not return on polling.
|
||||
const renderBegin = source.indexOf('render = function(list) {');
|
||||
const renderEnd = source.indexOf('\nfunction renderRouterView()', renderBegin);
|
||||
assert(renderBegin >= 0 && renderEnd > renderBegin);
|
||||
const identity = value => String(value ?? '');
|
||||
const empty = () => '';
|
||||
Object.assign(context, {
|
||||
syncRouterNotesState: empty, syncExpandedActionPanels: empty,
|
||||
groupName: () => 'Без группы', metricPlaceholder: identity, duration: identity,
|
||||
formatLoad: identity, formatMemory: identity, flashValueForRouter: empty,
|
||||
formatFlash: identity, temperatureValueForRouter: empty, routerSupportsWol: () => false,
|
||||
getWolState: () => ({open: false}), getTrafficState: () => ({open: false}),
|
||||
routerNotesPreview: empty, actionPanelId: id => 'actions-' + id,
|
||||
expandedActionPanels: new Set(), expandedCardDetails: new Set(),
|
||||
expandedGroupPickers: new Set(), openRouterGroups: new Set(['__ungrouped__']),
|
||||
mobileCardsMq: {matches: false}, authIsOwner: () => true, groupPickerButtonsHtml: empty,
|
||||
renderModelMetric: empty, modelGetsLegendBadge: () => false, metric: empty,
|
||||
statusRu: identity, ago: empty, metricHtml: empty, formatMemoryHtml: empty,
|
||||
memoryClass: empty, formatFlashHtml: empty, flashClass: empty,
|
||||
formatTemperatureHtml: empty, tempClass: empty, syncActionToggleStates: empty,
|
||||
});
|
||||
vm.runInContext(source.slice(renderBegin, renderEnd), context);
|
||||
for (const mobile of [false, true]) {
|
||||
context.mobileCardsMq.matches = mobile;
|
||||
for (const expanded of [false, true]) {
|
||||
context.expandedCardDetails.clear();
|
||||
if (expanded) context.expandedCardDetails.add('router-details-test');
|
||||
for (let refresh = 0; refresh < 3; refresh++) {
|
||||
context.render([{...router, name: 'Test router', online: true}]);
|
||||
assert(!/data-vps-(toggle|field|save)/.test(context.cards.innerHTML));
|
||||
assert(!context.cards.innerHTML.includes('Настроить VPS host'));
|
||||
assert(context.cards.innerHTML.includes('Test router'));
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log('VPS_HOST_CONTROLS_HIDDEN_OK: desktop, mobile, expanded cards and polling');
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
@@ -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"v110" in self.request("/")
|
||||
assert b"v111" in self.request("/")
|
||||
self.app.snapshot_router_states()
|
||||
|
||||
def __exit__(self, *args):
|
||||
|
||||
Reference in new issue
Block a user