1.0.0
Wydanie WGTools-Extended / release (push) Failing after 16s

This commit is contained in:
asminme committed 2026-10-30 00:35:08 +01:00
1 parent f5bdd7e21c
commit affe28ad71
110 files changed
+52936 -14

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
import pytest
from app.core import auth
def test_accounts_start_with_safe_access_and_can_be_scoped(tmp_path, monkeypatch):
monkeypatch.setattr(auth, "DATABASE_PATH", str(tmp_path / "users.db"))
admin = auth.create_user("admin", "password123")
user = auth.create_user("tester", "password123")
assert auth.get_user_access(admin["id"])["role"] == "admin"
assert auth.get_user_access(user["id"]) == {"role": "user", "interfaces": [], "permissions": {}}
auth.set_user_access(user["id"], "user", ["wg2", "wg1", "wg1"])
assert auth.get_user_access(user["id"])["interfaces"] == ["wg1", "wg2"]
auth.set_user_access(user['id'], 'user', ['wg1'], {'wg1':['add']})
assert auth.get_user_access(user['id'])['permissions'] == {'wg1':['add']}
with pytest.raises(ValueError):
auth.set_user_access(user["id"], "user", ["wg1;rm"])
with pytest.raises(ValueError):
auth.set_user_access(user["id"], "user", ["wgnode0"])
def test_legacy_accounts_keep_admin_access(tmp_path, monkeypatch):
monkeypatch.setattr(auth, "DATABASE_PATH", str(tmp_path / "legacy.db"))
user = auth.create_user("legacy", "password123")
assert auth.get_user_access(user["id"]) == {"role": "admin", "interfaces": [], "permissions": {}}
+56
View File
@@ -0,0 +1,56 @@
"""Exercise the authorization guard through the HTTP stack in an isolated process."""
import os
from pathlib import Path
import subprocess
import sys
import textwrap
def test_user_is_restricted_to_assigned_interface(tmp_path):
root = Path(__file__).resolve().parents[1]
env = dict(os.environ, WGTOOLS_DATABASE=str(tmp_path / "test.db"),
WGTOOLS_SESSION_KEY_FILE=str(tmp_path / "session.key"))
script = textwrap.dedent('''
from unittest.mock import patch
from fastapi.testclient import TestClient
import app.main as m
from app.core.auth import create_user, set_user_access
from app.core.preferences import update_branding
create_user('admin', 'password123')
user = create_user('tester', 'password123')
set_user_access(user['id'], 'user', ['wg1'])
update_branding('', '#123456', '')
def helper(action, payload=None, **kwargs):
if action == 'interfaces_list':
return {'ok': True, 'interfaces': [{'name': 'wg1'}, {'name': 'wg2'}]}
if action == 'snapshot':
return {'ok': True, 'config': {'interface': {'post_up': ['secret hook']}}, 'peers': []}
return {'ok': True}
with patch.object(m, 'run_helper', side_effect=helper), patch.object(m, 'merge_wireguard_last_seen', return_value=[]), patch.object(m, 'list_vps', return_value=[]):
c = TestClient(m.app)
assert 'WGTools' not in c.get('/login').text
assert c.post('/api/auth/login', json={'username':'tester','password':'password123'}).status_code == 200
client_page = c.get('/clients')
assert client_page.status_code == 200
assert 'Przekierowania portów' in client_page.text
assert 'href="/server"' not in client_page.text
assert c.post('/api/interfaces/delete', json={'interface':'wg1'}).status_code == 403
assert c.post('/api/server/config/apply', json={'content':''}).status_code == 403
assert c.post('/api/branding', json={}).status_code == 403
assert c.post('/api/update/upload', content=b'invalid').status_code == 403
assert c.get('/api/extended/ip-groups').status_code == 403
assert [x['name'] for x in c.get('/api/interfaces').json()['interfaces']] == ['wg1']
c.cookies.set('wgtools_interface', 'wg2')
assert c.get('/api/snapshot').status_code == 403
assert c.get('/api/extended/forwardings').status_code == 403
assert c.post('/api/clients/create', json={'name':'bad','type':'client'}).status_code == 403
c.cookies.set('wgtools_interface', 'wg1')
response = c.get('/api/snapshot')
assert response.status_code == 200
assert 'post_up' not in response.json()['config']['interface']
assert c.post('/api/clients/create', json={'name':'bad','type':'site_to_site','remote_networks':['10.1.0.0/16']}).status_code == 403
set_user_access(user['id'], 'user', ['wg1'], {'wg1':['add']})
assert c.post('/api/extended/forwardings', json={'public_ip':'192.0.2.1','public_port':1234,'target_ip':'10.0.0.2','target_port':1234,'protocol':'tcp'}).status_code == 403
assert c.post('/api/clients/update', json={'name':'peer','public_key':'x'*44}).status_code == 403
''')
subprocess.run([sys.executable, '-c', script], cwd=root, env=env, check=True, timeout=30)
+86
View File
@@ -0,0 +1,86 @@
from pathlib import Path
import runpy
import pytest
@pytest.fixture
def network(tmp_path, monkeypatch):
pytest.importorskip('fcntl')
module = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper'))
gl = module['extended_forward_add'].__globals__
configs = {
'wg1': '[Interface]\nAddress = 10.0.1.1/24\nListenPort = 51821\nPrivateKey = key\n[Peer]\nPublicKey = client1\nAllowedIPs = 10.0.1.2/32\n',
'wg2': '[Interface]\nAddress = 10.0.2.1/24\nListenPort = 51822\nPrivateKey = key\n[Peer]\nPublicKey = client2\nAllowedIPs = 10.0.2.2/32\n',
}
monkeypatch.setitem(gl, 'EXT_IP_GROUPS_PATH', tmp_path / 'groups.json')
monkeypatch.setitem(gl, '_configured_interface_names', lambda: set(configs))
monkeypatch.setitem(gl, '_extended_configured', lambda: set(configs))
monkeypatch.setitem(gl, '_extended_host_ips', lambda: {'192.0.2.10': 'eth0', '192.0.2.20': 'eth0'})
monkeypatch.setitem(gl, '_extended_listener_conflict', lambda *args: False)
monkeypatch.setitem(gl, 'read_config_text', lambda iface: configs[iface])
def apply(iface, payload):
configs[iface] = payload['content']
return {'ok': True}
monkeypatch.setitem(gl, 'raw_config_apply', apply)
return module, configs
def test_groups_share_addresses_and_enforce_conflicts(network):
m, configs = network
m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1','wg2']})
m['extended_ip_groups_set']({'name':'private','addresses':['192.0.2.20'],'interfaces':['wg2']})
forward = {'public_ip':'192.0.2.10','public_port':25565,'target_ip':'10.0.1.2','target_port':25565,'protocol':'both'}
added = m['extended_forward_add']('wg1', forward)['forward']
assert 'DNAT --to-destination 10.0.1.2:25565' in configs['wg1']
assert m['extended_forward_get']('wg1')['addresses'] == ['192.0.2.10']
with pytest.raises(ValueError, match='nie jest przypisany'):
m['extended_forward_add']('wg1', {**forward, 'public_ip':'192.0.2.20'})
with pytest.raises(ValueError, match='już używane'):
m['extended_forward_add']('wg2', {**forward, 'target_ip':'10.0.2.2', 'protocol':'tcp'})
with pytest.raises(ValueError, match='odebrałaby'):
m['extended_ip_groups_set']({'name':'shared', 'delete':True})
m['extended_forward_delete']('wg1', {'id':added['id']})
assert 'WGEXT-FORWARD' not in configs['wg1']
m['extended_ip_groups_set']({'name':'shared', 'delete':True})
def test_rejects_foreign_target_and_wireguard_port(network):
m, _ = network
m['extended_ip_groups_set']({'name':'shared','addresses':['192.0.2.10'],'interfaces':['wg1']})
forward = {'public_ip':'192.0.2.10','public_port':1234,'target_ip':'10.0.2.2','target_port':1234,'protocol':'tcp'}
with pytest.raises(ValueError, match='nie należy'):
m['extended_forward_add']('wg1', forward)
with pytest.raises(ValueError, match='używany przez WireGuard'):
m['extended_forward_add']('wg1', {**forward,'target_ip':'10.0.1.2','public_port':51822,'protocol':'udp'})
def test_wireguard_dump_accepts_disabled_keepalive(network, monkeypatch):
m, _ = network
gl = m['wg_dump'].__globals__
monkeypatch.setattr(gl['shutil'], 'which', lambda name: '/usr/bin/wg')
dump = 'private\tpublic\t51821\toff\npeer\t(none)\t(none)\t10.0.1.2/32\t0\t0\t0\toff\n'
monkeypatch.setitem(gl, 'run', lambda *args: (0, dump, ''))
assert m['wg_dump']('wg1')['peers']['peer']['persistent_keepalive_runtime'] == 0
def test_server_editor_preserves_extended_firewall_hooks(network):
m, _ = network
command = 'iptables -I FORWARD -i wg1 -m comment --comment wgext-forward-wg1-123 -j ACCEPT'
assert m['_managed_hook_kind'](command, 'wg1', {}, set()) is None
def test_migration_backup_includes_address_groups(network, tmp_path, monkeypatch):
m, _ = network
gl = m['_build_migration_archive'].__globals__
monkeypatch.setitem(gl, 'DATABASE_PATH', tmp_path / 'absent.db')
monkeypatch.setitem(gl, 'CLIENT_DIR', tmp_path / 'clients')
monkeypatch.setitem(gl, 'WG_DIR', tmp_path / 'wireguard')
monkeypatch.setitem(gl, 'SYSCTL_FILE', tmp_path / 'sysctl')
monkeypatch.setitem(gl, 'INTERFACES_META_PATH', tmp_path / 'interfaces.json')
monkeypatch.setitem(gl, 'GROUPS_PATH', tmp_path / 'client-groups.json')
(tmp_path / 'groups.json').write_text('{"test": {"addresses": [], "interfaces": []}}', encoding='utf8')
archive = m['_build_migration_archive']('wg1', tmp_path / 'backups')
import tarfile
with tarfile.open(archive, 'r:gz') as tar:
assert 'data/extended-ip-groups.json' in tar.getnames()
+31
View File
@@ -0,0 +1,31 @@
from pathlib import Path
import runpy
import pytest
@pytest.fixture
def helper(monkeypatch):
pytest.importorskip('fcntl')
module = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper'))
gl = module['extended_listen_apply'].__globals__
monkeypatch.setitem(gl, 'read_config_text', lambda iface: '[Interface]\nAddress = 10.0.0.1/24\nListenPort = 51821\nPrivateKey = key\n[Peer]\nPublicKey = peer\n')
monkeypatch.setitem(gl, 'parse_config', lambda text, iface: {'interface': {'listen_port': 51821}})
monkeypatch.setitem(gl, 'run', lambda cmd: (0, '[{"addr_info":[{"family":"inet","local":"192.0.2.10"}]}]', ''))
monkeypatch.setitem(gl, 'raw_config_apply', lambda iface, payload: {'ok': True, 'content': payload['content']})
return module
def test_listen_rules_cover_ipv4_and_ipv6(helper):
result = helper['extended_listen_apply']('wg1', {'address': '192.0.2.10', 'interface': 'eth0'})
config = result['content']
assert '--dport 51821 -i eth0 -d 192.0.2.10' in config
assert 'ip6tables -w -I INPUT 1' in config
assert 'wgext-listen-wg1-drop -j DROP' in config
assert config.index('PostDown') < config.index('[Peer]')
def test_listen_rejects_unassigned_or_invalid_inputs(helper):
for address, interface in [('192.0.2.11', 'eth0'), ('192.0.2.10', 'eth0;id'), ('bad', '')]:
with pytest.raises(ValueError):
helper['extended_listen_apply']('wg1', {'address': address, 'interface': interface})
+30
View File
@@ -0,0 +1,30 @@
from pathlib import Path
import runpy
import pytest
@pytest.fixture
def helper(monkeypatch):
pytest.importorskip('fcntl')
mod = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper'))
gl = mod['extended_snat_apply'].__globals__
config = '[Interface]\nAddress = 10.2.0.1/24\nPrivateKey = key\n\n[Peer]\nPublicKey = peer\n'
monkeypatch.setitem(gl, 'read_config_text', lambda iface: config)
monkeypatch.setitem(gl, 'parse_config', lambda text, iface: {'detected': {'vpn_network': '10.2.0.0/24', 'uplink_interface': 'eth0'}})
monkeypatch.setitem(gl, 'run', lambda cmd: (0, '[{"addr_info":[{"family":"inet","local":"192.0.2.10"}]}]', ''))
monkeypatch.setitem(gl, 'raw_config_apply', lambda iface, payload: {'ok': True, 'content': payload['content']})
return mod
def test_snat_uses_assigned_address_and_preserves_peers(helper):
result = helper['extended_snat_apply']('wg1', {'address': '192.0.2.10', 'uplink': 'eth0'})
assert 'iptables -t nat -I POSTROUTING 1 -s 10.2.0.0/24 -o eth0' in result['content']
assert '--to-source 192.0.2.10' in result['content']
assert result['content'].index('PostDown') < result['content'].index('[Peer]')
def test_snat_rejects_unassigned_and_invalid_address(helper):
for address, uplink in [('192.0.2.11', 'eth0'), ('192.0.2.10', 'eth0;id'), ('bad', 'eth0')]:
with pytest.raises(ValueError):
helper['extended_snat_apply']('wg1', {'address': address, 'uplink': uplink})
+15
View File
@@ -0,0 +1,15 @@
"""The fork must not contact the upstream update service."""
from pathlib import Path
import runpy
import pytest
def test_upstream_update_is_disabled():
pytest.importorskip('fcntl')
helper = runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper'))
with pytest.raises(RuntimeError, match='Aktualizacje online są wyłączone'):
helper['update_check']()
with pytest.raises(RuntimeError, match='Aktualizacje online są wyłączone'):
helper['update_apply']('wg0')
assert helper['update_notice']()['update_available'] is False
+40
View File
@@ -0,0 +1,40 @@
import json
from pathlib import Path
import pytest
from scripts import gitea_release
def test_release_creates_draft_uploads_and_publishes(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
Path('VERSION').write_text('1.2.3', encoding='utf-8')
for key, value in {'GITHUB_REF_NAME':'v1.2.3', 'GITHUB_SERVER_URL':'https://git.example', 'GITHUB_REPOSITORY':'owner/project', 'GITEA_RELEASE_TOKEN':'test-token'}.items():
monkeypatch.setenv(key, value)
calls = []
def archive(args, **kwargs):
if args[1] == 'archive':
path = next(arg.removeprefix('--output=') for arg in args if arg.startswith('--output='))
Path(path).write_bytes(b'test archive')
class Response:
def __enter__(self): return self
def __exit__(self, *args): pass
def read(self): return b'{"id": 42}'
def urlopen(request, timeout):
calls.append(request)
return Response()
monkeypatch.setattr(gitea_release.subprocess, 'run', archive)
monkeypatch.setattr(gitea_release, 'urlopen', urlopen)
gitea_release.main()
assert [r.method for r in calls] == ['POST', 'POST', 'PATCH']
assert json.loads(calls[0].data)['draft'] is True
assert b'test archive' in calls[1].data
assert json.loads(calls[2].data)['draft'] is False
def test_release_rejects_version_mismatch(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
Path('VERSION').write_text('1.0.0', encoding='utf-8')
monkeypatch.setenv('GITHUB_REF_NAME', 'v1.0.1')
with pytest.raises(ValueError, match='VERSION'):
gitea_release.main()
+42
View File
@@ -0,0 +1,42 @@
"""Prevent non-Russian, non-English help falling back to English again."""
from __future__ import annotations
import json
import unittest
from pathlib import Path
from app.core.help_content import HELP, get_help_sections
ROOT = Path(__file__).resolve().parents[1]
LANGUAGES = ('de', 'fr', 'it', 'es', 'pl')
class HelpTranslationTests(unittest.TestCase):
def test_all_five_help_dictionaries_loaded(self):
original = get_help_sections('en')
for language in LANGUAGES:
with self.subTest(language=language):
file = ROOT/'app/core/help_locales'/f'{language}.json'
self.assertTrue(file.is_file())
data = json.loads(file.read_text(encoding='utf8'))
self.assertEqual(data, get_help_sections(language))
self.assertEqual(len(data),len(original))
self.assertEqual([s['id'] for s in data], [s['id'] for s in original])
self.assertNotEqual(data[0]['title'], original[0]['title'])
self.assertNotEqual(data[0]['topics'][0]['paragraphs'][0],original[0]['topics'][0]['paragraphs'][0])
for section, ref_section in zip(data, original):
self.assertTrue(section['title'].strip())
self.assertTrue(section['intro'].strip())
self.assertEqual(len(section['topics']),len(ref_section['topics']))
for topic, reference in zip(section['topics'],ref_section['topics']):
self.assertTrue(topic['title'].strip())
self.assertTrue(all(x.strip() for x in topic['paragraphs']))
self.assertEqual(bool(topic['example_lines']),bool(reference['example_lines']))
self.assertEqual(bool(topic['warning']),bool(reference['warning']))
# Common technical terms such as Diagnostics can legitimately match English.
self.assertNotEqual(topic['paragraphs'][0],reference['paragraphs'][0],"untranslated help paragraph")
self.assertTrue(all(x.strip() for x in topic['bullets']))
def test_unknown_language_defaults_to_english(self):
self.assertEqual(get_help_sections('non-existent-language'), HELP['en'])
def test_version(self):
self.assertEqual((ROOT/'VERSION').read_text().strip(),'1.0.0')
if __name__ == '__main__':
unittest.main()
+21
View File
@@ -0,0 +1,21 @@
"""The bootstrap runs the local installer and never downloads upstream code."""
from pathlib import Path
import shutil
import subprocess
import pytest
ROOT = Path(__file__).resolve().parents[1]
def test_bootstrap_uses_local_source(tmp_path):
bash = shutil.which('bash')
if not bash:
pytest.skip('bash is required')
source = tmp_path / 'source'
(source / 'scripts').mkdir(parents=True)
shutil.copyfile(ROOT / 'install.sh', source / 'install.sh')
(source / 'scripts' / 'install.sh').write_text('#!/bin/sh\nprintf "local installer: %s" "$1"\n', encoding='utf-8')
result = subprocess.run([bash, str(source / 'install.sh'), 'test'], capture_output=True, text=True, check=True)
assert result.stdout == 'local installer: test'
assert 'KindMich/WGTools' not in (ROOT / 'install.sh').read_text(encoding='utf-8')
+86
View File
@@ -0,0 +1,86 @@
"""Regression tests for the v0.40.4 native candidate, no privileged side effects."""
from __future__ import annotations
import json
import re
import runpy
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
LANGS = ('en', 'ru', 'de', 'fr', 'it', 'es', 'pl')
class CandidateTests(unittest.TestCase):
def test_versions_and_locale_fallback_contract(self):
self.assertEqual((ROOT / 'VERSION').read_text().strip(), '1.0.0')
en = json.loads((ROOT/'app/locales/en.json').read_text())
self.assertGreaterEqual(len(en), 1098)
for lang in LANGS:
content=(ROOT/'app/locales'/f'{lang}.json').read_bytes()
self.assertEqual(content,(ROOT/'app/static'/f'{lang}.json').read_bytes())
self.assertEqual(content,(ROOT/'app/static/locales'/f'{lang}.json').read_bytes())
data=json.loads(content)
self.assertEqual(set(data),set(en),lang)
# Every supported language resolves every possible UI key through English.
merged={**en,**data}
self.assertEqual(set(merged),set(en))
for key,value in data.items():
self.assertEqual(set(re.findall(r'\{\w+\}',value)),
set(re.findall(r'\{\w+\}',en[key])),(lang,key))
def test_delete_returns_exact_client_name_for_audit(self):
helper=runpy.run_path(str(ROOT/'scripts/wgtools-helper'))
fun=helper['delete_client']
g=fun.__globals__
g.update({
'read_config_text':lambda iface:'[Interface]\n',
'parse_config':lambda text,iface:{'peers':[{'public_key':'PUBLICKEY','name':'Work laptop','remote_networks':[]}], 'detected':{}},
'replace_peer_block':lambda text,key,value:text,
'update_route_hooks':lambda text,*args:text,
'load_client_meta':lambda key:None,
'delete_client_meta':lambda key:None,
'sync_managed_client_policies':lambda text,iface:text,
'write_config_transaction':lambda *args:'/tmp/test-backup',
})
response=fun('wg0',{'public_key':'PUBLICKEY'})
self.assertEqual(response['name'],'Work laptop')
self.assertTrue(response['ok'])
def test_short_cache_and_no_runtime_tests(self):
helper=runpy.run_path(str(ROOT/'scripts/wgtools-helper'))
self.assertEqual(helper['UPDATE_NOTICE_MAX_AGE'],15*60)
installer=(ROOT/'scripts/install.sh').read_text()
self.assertIn('"$APP_DIR/tests"',installer)
self.assertIn('Preserving existing /etc/wgtools/wgtools.env',installer)
js=(ROOT/'app/static/js/app.js').read_text()
self.assertIn('topbar-theme-toggle',js)
self.assertIn('renderPeerTable(body,visiblePeers.map',js)
self.assertIn('topbar-update-notice',js)
def test_online_breathes_without_reset_and_icon_is_svg(self):
css=(ROOT/'app/static/css/app.css').read_text()
js=(ROOT/'app/static/js/app.js').read_text()
template=(ROOT/'app/templates/base.html').read_text()
self.assertIn('.status-dot.peer-status-dot.offline{\n animation:none!important;',css)
self.assertNotIn('animation:wgtools-peer-breathe',css)
self.assertIn('animation:wgtools-peer-online-breathe 2.4s ease-in-out infinite',css)
self.assertIn('inset:-2px;',css)
self.assertIn('50%{transform:scale(1.10);opacity:.88}',css)
self.assertNotIn('0 0 9px rgba(105,193,125,.42)',css)
self.assertIn('prefers-reduced-motion:reduce',css)
self.assertIn('renderPeerTable(body,rowsHtml,5)',js)
self.assertIn('theme-icon-sun',template)
self.assertIn('theme-icon-moon',template)
self.assertNotIn('id="topbar-theme-icon"',template)
self.assertIn('old.innerHTML!==next.innerHTML',js)
self.assertIn('a.className===b.className&&a.textContent===b.textContent',js)
self.assertNotIn('pulse-phase',js)
self.assertNotIn('wgtools-peer-online-ripple',css)
self.assertIn('animation:none!important',css)
if __name__=='__main__':
unittest.main()
+107
View File
@@ -0,0 +1,107 @@
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from app import telegram_bot
from app.core import audit
class Release405Tests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self._db = audit.DATABASE_PATH
audit.DATABASE_PATH = str(Path(self.tmp.name) / "audit.db")
audit.init_audit_database()
telegram_bot.PENDING.clear()
def tearDown(self):
audit.DATABASE_PATH = self._db
telegram_bot.PENDING.clear()
self.tmp.cleanup()
def test_audit_cursors_and_actor_across_admins(self):
for i in range(45):
audit.write_audit("admin" if i % 2 else "Telegram · @ops · ID 123", "client.created", object=f"wg0 · peer-{i}", result="created")
recent = audit.list_audit_page(limit=20)
self.assertEqual(len(recent["items"]), 20)
self.assertEqual(recent["items"][0]["object"], "wg0 · peer-44")
self.assertTrue(recent["has_older"])
self.assertFalse(recent["has_newer"])
older = audit.list_audit_page(before_id=recent["items"][-1]["id"])
self.assertEqual(len(older["items"]), 20)
self.assertTrue(older["has_newer"])
oldest = audit.list_audit_page(before_id=older["items"][-1]["id"])
self.assertEqual(len(oldest["items"]), 5)
self.assertFalse(oldest["has_older"])
newer = audit.list_audit_page(after_id=oldest["items"][0]["id"])
self.assertEqual([x["id"] for x in newer["items"]], [x["id"] for x in older["items"]])
self.assertNotIn("details", older["items"][0])
text, keyboard = telegram_bot.audit_screen("ru", recent)
self.assertIn("аудита", text)
self.assertIn("peer-44", text)
self.assertTrue(any(btn.get("callback_data", "").startswith("audit:before") for row in keyboard["inline_keyboard"] for btn in row))
def test_bot_appends_screens_and_confirmation_requires_fresh_prompt(self):
messages = []
def fake_send(token, chat_id, text, markup=None):
messages.append(text)
return {"message_id": 100 + len(messages)}
telegram_bot.PENDING[42] = {"step": "confirm_stop", "message_id": 17, "chat_id": 42}
with patch.object(telegram_bot, "send_message", fake_send), patch.object(telegram_bot, "edit_message") as edited:
telegram_bot.edit_or_send("token", 42, 17, "new screen", telegram_bot.back_keyboard("en"))
self.assertEqual(telegram_bot.PENDING[42]["message_id"], 101)
self.assertEqual(messages, ["new screen"])
edited.assert_not_called()
def test_stale_telegram_confirmation_cannot_restart_interface(self):
user = {"id": 42, "language_code": "en"}
def cb(data, mid):
return {"callback_query": {"id": "cb", "data": data, "from": user,
"message": {"message_id": mid, "chat": {"id": 42, "type": "private"}}}}
actions = []
issued = []
def fake_send(token, chat, text, markup=None):
issued.append((text, markup))
return {"message_id": 300 + len(issued)}
with patch.object(telegram_bot, "send_message", fake_send), \
patch.object(telegram_bot, "run_helper", side_effect=lambda action, *args, **kwargs: actions.append(action) or {"ok":True}), \
patch.object(telegram_bot, "answer_callback"), \
patch.object(telegram_bot, "clear_inline_keyboard"):
settings={"language":"en", "allowed_user_ids":[42]}
telegram_bot.handle_update(cb("stop", 9), settings, "token")
self.assertEqual(len(issued), 1)
confirmation_id=301
telegram_bot.handle_update(cb("stop_yes", 9), settings, "token")
self.assertNotIn("wireguard_stop", actions)
telegram_bot.handle_update(cb("stop_yes", confirmation_id), settings, "token")
# The current confirmation works once; an earlier button cannot act.
self.assertEqual(actions.count("wireguard_stop"), 1)
telegram_bot.handle_update(cb("stop_yes", confirmation_id), settings, "token")
self.assertEqual(actions.count("wireguard_stop"), 1)
def test_audit_permission_gate(self):
event = {"callback_query": {"id": "x", "data": "audit:latest", "from": {"id": 33, "language_code": "en"}, "message": {"message_id": 2, "chat": {"id": 33, "type": "private"}}}}
sent = []
with patch.object(telegram_bot, "send_message", lambda *a, **kw: sent.append(a[2])), patch.object(telegram_bot,"answer_callback"):
telegram_bot.handle_update(event, {"language":"en", "allowed_user_ids":[]}, "token")
self.assertEqual(len(sent), 1)
self.assertIn("Access denied", sent[0])
def test_theme_and_audit_global_modal(self):
root = Path(__file__).resolve().parents[1]
base = (root / "app/templates/base.html").read_text()
settings = (root / "app/templates/settings.html").read_text()
js = (root / "app/static/js/app.js").read_text()
self.assertIn('id="topbar-audit-button"',base)
self.assertIn('id="audit-modal"',base)
self.assertNotIn('id="audit-modal"',settings)
self.assertNotIn('id="sidebar-update-notice"',base)
self.assertIn('id="sidebar-collapse-button"',base)
self.assertIn("button.dataset.tooltip=label;button.removeAttribute('title')",js)
self.assertNotIn("if(page!=='settings'||!body)return",js)
if __name__ == "__main__":
unittest.main()
+176
View File
@@ -0,0 +1,176 @@
from __future__ import annotations
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from app.core import audit
from app import telegram_bot
USER = {"id": 424242, "username": "audit_tester", "language_code": "en"}
CHAT_ID = 1001
PUBLIC_KEY = "test-public-key"
def callback(data: str, user: dict | None = None, message_id: int = 10) -> dict:
return {
"callback_query": {
"id": f"cb-{message_id}",
"data": data,
"from": dict(user or USER),
"message": {
"message_id": message_id,
"chat": {"id": CHAT_ID, "type": "private"},
},
}
}
def message(text: str, user: dict | None = None) -> dict:
return {
"message": {
"text": text,
"from": dict(user or USER),
"chat": {"id": CHAT_ID, "type": "private"},
}
}
class TelegramAuditTests(unittest.TestCase):
def setUp(self) -> None:
self.tmp = tempfile.TemporaryDirectory()
audit.DATABASE_PATH = str(Path(self.tmp.name) / "wgtools-test.db")
audit.init_audit_database()
telegram_bot.PENDING.clear()
telegram_bot.SELECTED_INTERFACES.clear()
self.peers: list[dict] = []
self.settings = {
"allowed_user_ids": [USER["id"]],
"language": "en",
"default_endpoint": "vpn.example.com",
"default_dns": ["1.1.1.1"],
}
def tearDown(self) -> None:
telegram_bot.PENDING.clear()
telegram_bot.SELECTED_INTERFACES.clear()
self.tmp.cleanup()
def fake_helper(self, action: str, payload: dict | None = None, *, interface: str | None = None):
iface = interface or "wg0"
if action == "snapshot":
return {
"ok": True,
"interface": iface,
"listen_port": 51820,
"config": {"interface": {"listen_port": 51820}},
"client_groups": [],
"peers": [dict(peer) for peer in self.peers],
}
if action == "create_client":
data = payload or {}
peer = {
"name": str(data.get("name") or "Peer"),
"public_key": PUBLIC_KEY,
"vpn_address": "10.0.0.2/32",
"managed": True,
}
self.peers.append(peer)
return {"ok": True, **peer}
if action == "client_config":
return {"ok": True, "filename": "audit-test.conf", "config": "[Interface]\nPrivateKey = SHOULD_NOT_BE_AUDITED\n"}
if action == "delete_client":
key = str((payload or {}).get("public_key") or "")
self.peers[:] = [peer for peer in self.peers if str(peer.get("public_key") or "") != key]
return {"ok": True, "name": "telegram-client"}
if action in {"wireguard_start", "wireguard_stop", "wireguard_restart"}:
return {"ok": True}
raise AssertionError(f"Unexpected helper action: {action}")
def bot_patches(self):
return patch.multiple(
telegram_bot,
run_helper=self.fake_helper,
send_message=lambda *args, **kwargs: {"message_id": 99},
edit_message=lambda *args, **kwargs: None,
answer_callback=lambda *args, **kwargs: None,
clear_inline_keyboard=lambda *args, **kwargs: None,
send_client_files=lambda *args, **kwargs: None,
get_preferences=lambda: {"online_threshold_seconds": 180},
)
def test_create_and_delete_client_are_audited_with_telegram_identity(self) -> None:
with self.bot_patches():
telegram_bot.handle_update(callback("create", message_id=1), self.settings, "token")
telegram_bot.handle_update(message("telegram-client"), self.settings, "token")
telegram_bot.handle_update(callback("delete", message_id=2), self.settings, "token")
telegram_bot.handle_update(callback(f"delpick:{PUBLIC_KEY}", message_id=3), self.settings, "token")
telegram_bot.handle_update(callback(f"delyes:{PUBLIC_KEY}", message_id=99), self.settings, "token")
# Read-only navigation must not create audit noise.
telegram_bot.handle_update(callback("status", message_id=5), self.settings, "token")
telegram_bot.handle_update(callback("clients", message_id=6), self.settings, "token")
items = audit.list_audit(50)
telegram_items = [item for item in items if item["username"].startswith("Telegram")]
self.assertEqual([item["action"] for item in reversed(telegram_items)], ["client.created", "client.deleted"])
for item in telegram_items:
self.assertEqual(item["username"], "Telegram · @audit_tester · ID 424242")
details = json.loads(item["details"])
self.assertEqual(details["source"], "telegram")
self.assertEqual(details["telegram_user_id"], USER["id"])
self.assertEqual(details["telegram_username"], USER["username"])
self.assertEqual(details["interface"], "wg0")
self.assertNotIn("PrivateKey", item["details"])
self.assertNotIn("SHOULD_NOT_BE_AUDITED", item["details"])
def test_wireguard_service_controls_are_audited(self) -> None:
with self.bot_patches():
telegram_bot.handle_update(callback("start", message_id=20), self.settings, "token")
telegram_bot.handle_update(callback("stop", message_id=21), self.settings, "token")
telegram_bot.handle_update(callback("stop_yes", message_id=99), self.settings, "token")
telegram_bot.handle_update(callback("restart", message_id=23), self.settings, "token")
telegram_bot.handle_update(callback("restart_yes", message_id=99), self.settings, "token")
items = list(reversed(audit.list_audit(20)))
self.assertEqual(
[item["action"] for item in items],
["wireguard.started", "wireguard.stopped", "wireguard.restarted"],
)
self.assertTrue(all(item["username"] == "Telegram · @audit_tester · ID 424242" for item in items))
def test_denied_state_change_is_audited_but_read_only_denial_is_not(self) -> None:
denied_settings = {**self.settings, "allowed_user_ids": []}
with self.bot_patches():
telegram_bot.handle_update(callback("status", message_id=10), denied_settings, "token")
telegram_bot.handle_update(callback("start", message_id=11), denied_settings, "token")
items = audit.list_audit(20)
self.assertEqual(len(items), 1)
self.assertEqual(items[0]["action"], "telegram.action_denied")
self.assertEqual(items[0]["result"], "denied")
self.assertIn("WireGuard start", items[0]["object"])
self.assertIn("ID 424242", items[0]["username"])
def test_failure_text_is_redacted_before_storage(self) -> None:
secret_key = "A" * 43 + "="
telegram_bot.telegram_audit_failure(
USER,
"Create client",
RuntimeError(f"PrivateKey={secret_key} bot token 123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"),
interface="wg0",
object="safe-client",
)
item = audit.list_audit(1)[0]
self.assertEqual(item["action"], "telegram.action_failed")
self.assertNotIn(secret_key, item["result"])
self.assertNotIn("123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef", item["result"])
self.assertIn("[redacted]", item["result"])
if __name__ == "__main__":
unittest.main()
+73
View File
@@ -0,0 +1,73 @@
"""Regression checks for Telegram audit navigation and HTML presentation (v0.40.5)."""
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from app import telegram_bot as bot
from app.core import audit
class AuditPresentationTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.prev_db = audit.DATABASE_PATH
audit.DATABASE_PATH = str(Path(self.tmp.name) / "audit.db")
audit.init_audit_database()
def tearDown(self):
audit.DATABASE_PATH = self.prev_db
self.tmp.cleanup()
def test_menu_label_and_clean_arrows(self):
menu = bot.main_keyboard("ru", 42)["inline_keyboard"]
audit_button = next(btn for row in menu for btn in row if btn["callback_data"] == "audit:latest")
self.assertEqual(audit_button["text"], "🧾 Аудит")
for i in range(45):
audit.write_audit("admin", "client.created", object=f"wg0 · test-{i}", result="created")
newest = audit.list_audit_page(limit=20)
newest_text, newest_kb = bot.audit_screen("ru", newest)
self.assertIn("<b>", newest_text)
self.assertIn("<code>", newest_text)
self.assertIn("test-44", newest_text)
self.assertEqual(len(newest["items"]), 20)
self.assertEqual([b["text"] for row in newest_kb["inline_keyboard"] for b in row], ["➡️", "⬅️ Меню"])
self.assertTrue(all(b["callback_data"] != "audit:latest" for row in newest_kb["inline_keyboard"] for b in row))
old = audit.list_audit_page(before_id=newest["items"][-1]["id"])
old_txt, old_kb = bot.audit_screen("ru", old)
self.assertEqual([b["text"] for row in old_kb["inline_keyboard"] for b in row], ["⬅️", "➡️", "⬅️ Меню"])
self.assertEqual(old_kb["inline_keyboard"][0][0]["callback_data"], f"audit:after:{old['items'][0]['id']}")
self.assertEqual(old_kb["inline_keyboard"][0][1]["callback_data"], f"audit:before:{old['items'][-1]['id']}")
self.assertLess(len(old_txt), 4096)
def test_audit_html_escapes_untrusted_text(self):
audit.write_audit('<admin & "root">', "client.deleted", object="wg0 · a&<b>test</b>", result="<bad>")
rendered, keyboard = bot.audit_screen("ru", audit.list_audit_page())
self.assertIn("&lt;admin &amp; &quot;root&quot;&gt;", rendered)
self.assertIn("a&amp;&lt;b&gt;test&lt;/b&gt;", rendered)
self.assertIn("&lt;bad&gt;", rendered)
self.assertNotIn("<bad>", rendered)
self.assertNotIn("<b>test</b>", rendered)
self.assertIn("🗑️", rendered)
def test_long_audit_still_keeps_20_entries_within_telegram_limit(self):
for i in range(20):
audit.write_audit("&" * 119, "client.updated", object="&" * 230, result="&" * 230)
text, _ = bot.audit_screen("ru", audit.list_audit_page())
self.assertLess(len(text), 4096)
self.assertEqual(text.count("<code>"), 20)
self.assertEqual(text.count("✏️"), 20)
def test_audit_messages_use_html_but_normal_messages_remain_plain(self):
payloads = []
with patch.object(bot, "telegram_api_call", side_effect=lambda token, action, payload, **kw: payloads.append((action, payload)) or {"message_id":99}):
bot.send_message("t", 42, "Plain message")
bot.send_message("t", 42, "<b>Formatted</b>", parse_mode="HTML")
self.assertNotIn("parse_mode", payloads[0][1])
self.assertEqual(payloads[1][1]["parse_mode"], "HTML")
if __name__ == "__main__":
unittest.main()
+47
View File
@@ -0,0 +1,47 @@
import io
from pathlib import Path
import runpy
import tarfile
import pytest
@pytest.fixture
def helper():
pytest.importorskip('fcntl')
return runpy.run_path(str(Path(__file__).resolve().parents[1] / 'scripts/wgtools-helper'))
def archive(path, entries):
with tarfile.open(path, 'w:gz') as tar:
for name, content in entries:
item = tarfile.TarInfo(name)
if content is None:
item.type = tarfile.SYMTYPE
item.linkname = '/etc/passwd'
tar.addfile(item)
else:
item.size = len(content)
tar.addfile(item, io.BytesIO(content))
def test_uploaded_package_rejects_paths_and_links(helper, tmp_path):
for name, content in [('../escape', b'bad'), ('link', None), ('/etc/passwd', b'bad')]:
package = tmp_path / 'unsafe.bin'
archive(package, [(name, content)])
with pytest.raises(ValueError):
helper['_extract_uploaded_update'](package, tmp_path / 'dest')
assert not (tmp_path / 'escape').exists()
def test_uploaded_package_requires_newer_version(helper, tmp_path, monkeypatch):
gl = helper['_uploaded_update_validate'].__globals__
monkeypatch.setitem(gl, '_validate_update_source', lambda *args: None)
monkeypatch.setitem(gl, '_current_wgtools_version', lambda: '1.2.3')
package = tmp_path / 'update.bin'
archive(package, [('VERSION', b'1.2.4\n')])
_, version = helper['_uploaded_update_validate'](package, tmp_path / 'good')
assert version == '1.2.4'
archive(package, [('VERSION', b'1.2.3\n')])
with pytest.raises(ValueError, match='nowsza'):
helper['_uploaded_update_validate'](package, tmp_path / 'old')