mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-28 19:06:19 -05:00
Torrents reach the Internet only through a fail-closed VPN (WireGuard or OpenVPN, any provider), so peers never see a WROLPi's own address. - A network namespace (Pi/Debian) or the vpn container (Docker) with an nftables kill switch; NAT-PMP or fixed port forwarding. - qBittorrent inside it, sandboxed; torrents kept in config/torrents/. - Torrent download form, Torrents page, Share as torrent, nav warning, and VPN settings in both Controller UIs. - Help docs: Torrents, and The VPN for Torrents. QA'd on a Raspberry Pi with a real provider over WireGuard and OpenVPN. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
148 lines
8 KiB
Python
148 lines
8 KiB
Python
"""Share as torrent: make a torrent of a file or directory in the library, and seed it."""
|
|
import asyncio
|
|
from http import HTTPStatus
|
|
from unittest import mock
|
|
|
|
import pytest
|
|
|
|
from modules.torrents import lib, share
|
|
from modules.torrents.test.test_adding import TORRENT, HASH
|
|
from wrolpi.errors import ValidationError
|
|
|
|
|
|
@pytest.fixture
|
|
def planet(test_directory):
|
|
path = test_directory / 'maps' / 'planet.pmtiles'
|
|
path.parent.mkdir(parents=True)
|
|
path.write_bytes(b'tiles')
|
|
return path
|
|
|
|
|
|
class TestCheck:
|
|
|
|
def test_share_path(self, test_directory, planet):
|
|
assert share.check_share_path('maps/planet.pmtiles') == planet
|
|
assert share.check_share_path('maps/') == planet.parent
|
|
|
|
@pytest.mark.parametrize('path,message', [
|
|
('', 'Choose'), ('missing.bin', 'does not exist'), ('../outside', 'media directory'),
|
|
('config/torrents', 'config'), ('empty', 'no files'),
|
|
])
|
|
def test_refused(self, test_directory, planet, path, message):
|
|
(test_directory / 'empty').mkdir()
|
|
(test_directory / 'config' / 'torrents').mkdir(parents=True, exist_ok=True)
|
|
with pytest.raises(ValidationError, match=message):
|
|
share.check_share_path(path)
|
|
|
|
@pytest.mark.parametrize('path', ['.', './', '/', 'maps/..', 'config', 'config/vpn'])
|
|
def test_never_the_config(self, test_directory, planet, path):
|
|
(test_directory / 'config' / 'vpn').mkdir(parents=True, exist_ok=True)
|
|
(test_directory / 'config' / 'vpn' / 'wireguard.conf').write_text('PrivateKey = secret')
|
|
with pytest.raises(ValidationError):
|
|
share.check_share_path(path)
|
|
|
|
def test_links_out_are_refused(self, test_directory, planet):
|
|
(test_directory / 'config' / 'vpn').mkdir(parents=True, exist_ok=True)
|
|
(test_directory / 'config' / 'vpn' / 'wireguard.conf').write_text('PrivateKey = secret')
|
|
(test_directory / 'maps' / 'keys').symlink_to(test_directory / 'config' / 'vpn')
|
|
with pytest.raises(ValidationError, match='links to a folder'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'keys').unlink()
|
|
(test_directory / 'maps' / 'hosts').symlink_to('/etc/hosts')
|
|
with pytest.raises(ValidationError, match='outside the library'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'hosts').unlink()
|
|
# A link to the library itself would publish everything.
|
|
(test_directory / 'maps' / 'all').symlink_to(test_directory)
|
|
with pytest.raises(ValidationError, match='links to a folder'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'all').unlink()
|
|
# A link to a folder could lead anywhere (its own links are not walked).
|
|
(test_directory / 'videos').mkdir()
|
|
(test_directory / 'maps' / 'videos').symlink_to(test_directory / 'videos')
|
|
with pytest.raises(ValidationError, match='links to a folder'):
|
|
share.check_share_path('maps')
|
|
(test_directory / 'maps' / 'videos').unlink()
|
|
# A link to a file elsewhere in the library is fine; one to a file in config/ is not.
|
|
(test_directory / 'videos' / 'a.mp4').write_bytes(b'video')
|
|
(test_directory / 'maps' / 'a.mp4').symlink_to(test_directory / 'videos' / 'a.mp4')
|
|
assert share.check_share_path('maps') == planet.parent
|
|
(test_directory / 'maps' / 'key').symlink_to(test_directory / 'config' / 'vpn' / 'wireguard.conf')
|
|
with pytest.raises(ValidationError, match='config directory'):
|
|
share.check_share_path('maps')
|
|
|
|
def test_urls(self):
|
|
assert share.check_trackers(['udp://t.example:1337/announce', ' https://t.example/announce ', '',
|
|
'udp://t.example:1337/announce']) == \
|
|
['udp://t.example:1337/announce', 'https://t.example/announce']
|
|
assert share.check_web_seeds(['https://cdn.example/planet.pmtiles']) == ['https://cdn.example/planet.pmtiles']
|
|
for bad in ('ftp://t.example/', 'udp://', 'https://a.example/x|https://b.example/y', 'not a url'):
|
|
with pytest.raises(ValidationError):
|
|
share.check_trackers([bad])
|
|
with pytest.raises(ValidationError):
|
|
share.check_web_seeds(['udp://t.example:1337/announce'])
|
|
|
|
|
|
async def test_share(test_torrents_config, planet, fake_qbittorrent):
|
|
client = fake_qbittorrent(tags=[lib.TAG], created=TORRENT, creator_statuses=[
|
|
{'status': 'Running', 'progress': 40}, {'status': 'Finished', 'progress': None}])
|
|
job = mock.Mock()
|
|
job.cancel_requested.return_value = False
|
|
with mock.patch.object(share, 'get_current_job', lambda: job), mock.patch.object(share, 'POLL_SECONDS', 0):
|
|
result = await share.share_torrent('maps/planet.pmtiles', ['udp://t.example:1337/announce'],
|
|
['https://cdn.example/planet.pmtiles'], client=client)
|
|
assert result['hash'] == HASH
|
|
assert lib.magnet_identity(result['magnet'])[0] == HASH
|
|
assert ('create_torrent', str(planet), ['udp://t.example:1337/announce'],
|
|
['https://cdn.example/planet.pmtiles']) in client.calls
|
|
job.set_progress.assert_called_with(40)
|
|
# Seeded from where the files are, without hashing them again; the creator's task is cleaned up.
|
|
assert ('skip_checking', str(planet.parent)) in client.calls
|
|
assert ('delete_torrent_creator_task', 'task-1') in client.calls
|
|
entity = test_torrents_config.get(HASH)
|
|
assert (entity['save_path'], entity['complete']) == ('maps', True)
|
|
assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT
|
|
|
|
|
|
async def test_share_failed(test_torrents_config, planet, fake_qbittorrent):
|
|
client = fake_qbittorrent(tags=[lib.TAG], creator_statuses=[{'status': 'Failed', 'errorMessage': 'disk error'}])
|
|
with pytest.raises(lib.QBittorrentError, match='disk error'):
|
|
await share.share_torrent('maps/planet.pmtiles', [], [], client=client)
|
|
assert ('delete_torrent_creator_task', 'task-1') in client.calls
|
|
assert test_torrents_config.get(HASH) is None
|
|
|
|
|
|
async def test_share_cancelled(test_torrents_config, planet, fake_qbittorrent):
|
|
client = fake_qbittorrent(tags=[lib.TAG], creator_statuses=[{'status': 'Running', 'progress': 10}])
|
|
job = mock.Mock()
|
|
job.cancel_requested.return_value = True
|
|
with mock.patch.object(share, 'get_current_job', lambda: job), pytest.raises(asyncio.CancelledError):
|
|
await share.share_torrent('maps/planet.pmtiles', [], [], client=client)
|
|
# Stops qBittorrent hashing.
|
|
assert ('delete_torrent_creator_task', 'task-1') in client.calls
|
|
assert not [c for c in client.calls if c[0] == 'add']
|
|
|
|
|
|
async def test_share_api(test_torrents_config, async_client, planet, test_wrolpi_config):
|
|
with mock.patch.object(share, 'enqueue_job', return_value='job-1') as enqueue_job:
|
|
request, response = await async_client.post('/api/torrents/share', json={
|
|
'path': 'maps/planet.pmtiles', 'trackers': ['udp://t.example:1337/announce'],
|
|
'web_seeds': ['https://cdn.example/planet.pmtiles'], 'remember_trackers': True})
|
|
assert response.status_code == HTTPStatus.CREATED, response.json
|
|
assert response.json == {'job_id': 'job-1'}
|
|
assert enqueue_job.call_args.kwargs == dict(
|
|
description='Make a torrent of maps/planet.pmtiles', path='maps/planet.pmtiles',
|
|
trackers=['udp://t.example:1337/announce'], web_seeds=['https://cdn.example/planet.pmtiles'])
|
|
# Offered next time.
|
|
assert lib.get_wrolpi_config().torrent_trackers == ['udp://t.example:1337/announce']
|
|
|
|
request, response = await async_client.post('/api/torrents/share', json={
|
|
'path': 'config', 'trackers': ['udp://other.example:1/announce'], 'remember_trackers': True})
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
# A refused request changes nothing.
|
|
assert lib.get_wrolpi_config().torrent_trackers == ['udp://t.example:1337/announce']
|
|
|
|
|
|
def test_default_trackers(test_wrolpi_config):
|
|
assert lib.get_wrolpi_config().torrent_trackers == [
|
|
'udp://tracker.opentrackr.org:1337/announce', 'udp://tracker.torrent.eu.org:451/announce']
|