captive portal: address review

* React: re-read the hotspot address whenever the HotspotToggle starts or
  stops the hotspot, matching the fallback UI's refresh-on-status.
* A WPA3 start that reverts to WPA2 leaves the hotspot up, so it now gets
  the captive portal address correction too.
* The corrective `nmcli connection up` logs a warning on a non-zero exit;
  dnsmasq would otherwise keep the old address silently.
* HotspotStatusResponse.captive_portal defaults to true like everywhere else.
* Trim design narrative from the module docstring and React comments.
* The include-before-activate test now observes the include at the moment
  of the `nmcli ... hotspot` call instead of inferring from call order.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-09-13 19:33:51 -06:00
parent 6bea09600e
commit 85c27b91df
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
6 changed files with 118 additions and 28 deletions

View file

@ -19,7 +19,7 @@ import {
toast,
} from "../ui";
import {APIButton, BluetoothToggle, DesktopToggle, DirectorySearch, HandPointMessage, HotspotToggle, InfoMessage, ThrottleToggle, Toggle, VncToggle,} from "../Common";
import {useDockerized, useMediaDirectory} from "../../hooks/customHooks";
import {useDockerized, useHotspot, useMediaDirectory} from "../../hooks/customHooks";
import {Media} from "../../contexts/contexts";
import {
addFstabEntry,
@ -1463,8 +1463,8 @@ function HotspotSettingsForm() {
const [loading, setLoading] = React.useState(true);
const [saving, setSaving] = React.useState(false);
const [qrOpen, setQrOpen] = React.useState(false);
// Hotspot clients need this address to reach the WROLPi; the captive portal page tells them.
const [hotspotStatus, setHotspotStatus] = React.useState(null);
const {on: hotspotOn} = useHotspot();
React.useEffect(() => {
const fetchSettings = async () => {
@ -1487,7 +1487,7 @@ function HotspotSettingsForm() {
fetchSettings();
}, []);
// The address is only meaningful while the hotspot is up; it is optional information.
// Re-read the address whenever the sibling HotspotToggle starts or stops the hotspot.
React.useEffect(() => {
if (dockerized) {
return;
@ -1507,7 +1507,7 @@ function HotspotSettingsForm() {
return () => {
cancelled = true;
};
}, [dockerized]);
}, [dockerized, hotspotOn]);
// The supported protocols depend on the selected device's hardware.
React.useEffect(() => {

View file

@ -159,8 +159,9 @@ describe('ControllerPage', () => {
beforeEach(() => {
jest.clearAllMocks();
// Reset useDockerized to false for regular tests
const {useDockerized} = require('../../hooks/customHooks');
const {useDockerized, useHotspot} = require('../../hooks/customHooks');
useDockerized.mockReturnValue(false);
useHotspot.mockReturnValue({on: true, setHotspot: jest.fn()});
// resetMocks clears module-factory implementations, so configure hotspot mocks here.
const controllerApi = require('../../api/controller');
controllerApi.getHotspotSettings.mockResolvedValue(
@ -284,6 +285,37 @@ describe('ControllerPage', () => {
expect(screen.getByText(/Welcome page: http:\/\/10\.42\.0\.1\/portal/)).toBeInTheDocument();
});
test('hotspot address is re-read when the hotspot is toggled', async () => {
const controllerApi = require('../../api/controller');
const {useHotspot} = require('../../hooks/customHooks');
useHotspot.mockReturnValue({on: false, setHotspot: jest.fn()});
controllerApi.getHotspotStatus.mockResolvedValue(
{enabled: false, available: true, device: 'wlan0', ip: null, captive_portal: true, portal_url: null});
const {rerender} = renderControllerPage();
await screen.findByLabelText('Captive portal');
expect(controllerApi.getHotspotStatus).toHaveBeenCalledTimes(1);
expect(screen.queryByText('10.42.0.1')).not.toBeInTheDocument();
// The sibling HotspotToggle starts the hotspot.
useHotspot.mockReturnValue({on: true, setHotspot: jest.fn()});
controllerApi.getHotspotStatus.mockResolvedValue(
{enabled: true, available: true, device: 'wlan0', ip: '10.42.0.1', captive_portal: true,
portal_url: 'http://10.42.0.1/portal'});
rerender(
<BrowserRouter>
<MantineProvider theme={mantineTheme} cssVariablesResolver={cssVariablesResolver}>
<ThemeContext.Provider value={defaultTheme}>
<SettingsContext.Provider value={defaultSettings}>
<ControllerPage/>
</SettingsContext.Provider>
</ThemeContext.Provider>
</MantineProvider>
</BrowserRouter>
);
expect(await screen.findByText('10.42.0.1')).toBeInTheDocument();
expect(controllerApi.getHotspotStatus).toHaveBeenCalledTimes(2);
});
test('hotspot protocol dropdown only offers WPA2 on a Raspberry Pi', async () => {
const {getHotspotProtocols} = require('../../api/controller');
getHotspotProtocols.mockResolvedValue({device: 'wlan0', protocols: ['wpa2']});
@ -303,6 +335,7 @@ describe('DiskSection primary unmount', () => {
const controllerApi = require('../../api/controller');
beforeEach(() => {
require('../../hooks/customHooks').useHotspot.mockReturnValue({on: false, setHotspot: jest.fn()});
controllerApi.getDisks.mockResolvedValue([
{
name: 'sda1',
@ -381,8 +414,9 @@ describe('groupServices', () => {
describe('ControllerPage in Docker mode', () => {
beforeEach(() => {
jest.clearAllMocks();
const {useDockerized} = require('../../hooks/customHooks');
const {useDockerized, useHotspot} = require('../../hooks/customHooks');
useDockerized.mockReturnValue(true);
useHotspot.mockReturnValue({on: false, setHotspot: jest.fn()});
});
test('hides reboot/shutdown buttons in Docker mode', async () => {

View file

@ -157,7 +157,7 @@ class HotspotStatusResponse(BaseModel):
ssid: Optional[str] = Field(default=None, description="Hotspot SSID when enabled")
device: Optional[str] = Field(default=None, description="WiFi device name")
ip: Optional[str] = Field(default=None, description="Hotspot IPv4 address when enabled")
captive_portal: bool = Field(default=False, description="Whether the captive portal is enabled")
captive_portal: bool = Field(default=True, description="Whether the captive portal is enabled")
portal_url: Optional[str] = Field(default=None, description="Landing page URL when the hotspot is up")

View file

@ -530,6 +530,8 @@ def start_hotspot() -> dict:
capture_output=True, text=True, timeout=30,
)
if revert_modify.returncode == 0 and revert_up.returncode == 0:
# The hotspot is up (as WPA2), so it still needs its captive portal address.
_fix_captive_portal_ip(device)
return {"success": False,
"error": f"WPA3 is not supported by {device}; hotspot reverted to WPA2: {error}"}
revert_error = (revert_modify.stderr if revert_modify.returncode != 0 else revert_up.stderr).strip()
@ -572,7 +574,10 @@ def _fix_captive_portal_ip(device: str):
if not captive_portal_lib.apply_dnsmasq_config(ip):
return
try:
subprocess.run(["nmcli", "connection", "up", "Hotspot"], capture_output=True, text=True, timeout=30)
up = subprocess.run(["nmcli", "connection", "up", "Hotspot"], capture_output=True, text=True, timeout=30)
if up.returncode != 0:
logger.warning("Could not re-activate hotspot for captive portal; dnsmasq still serves the old"
" address: %s", up.stderr.strip())
except (subprocess.SubprocessError, FileNotFoundError) as e:
logger.warning("Could not re-activate hotspot for captive portal: %s", e)

View file

@ -1,16 +1,6 @@
"""
Hotspot captive portal.
Phones confirm Internet access after joining WiFi by fetching a fixed plain-HTTP URL and
expecting a fixed reply. Any other reply means "there is a sign-in page here", and the phone
shows it. The hotspot's DNS (NetworkManager's dnsmasq) answers those probe hostnames with the
hotspot's own address, the probes land on the Controller (port 80), and the Controller redirects
them to a landing page that shows the WROLPi's address.
Only the probe hostnames are hijacked. NetworkManager's shared mode forwards other names (and
traffic) to whatever uplink the WROLPi has, and a wildcard would break that.
Native RPi/Debian only: Docker has no hotspot, no host NetworkManager, and no port 80.
Hotspot captive portal: the dnsmasq include which points OS connectivity-probe hostnames at this
WROLPi, so devices that join the hotspot are shown its address. Native only (Docker has no hotspot).
"""
import json
import logging
@ -22,7 +12,8 @@ from controller.lib.config import get_config_value, is_docker_mode
logger = logging.getLogger(__name__)
# Hostnames the major operating systems probe. Resolved to the hotspot IP by dnsmasq.
# Hostnames the major operating systems probe for Internet access. Only these are hijacked: a
# wildcard would break the hotspot's forwarding of everything else to the WROLPi's uplink.
PROBE_HOSTS = (
'captive.apple.com', # iOS / macOS
'connectivitycheck.gstatic.com', # Android

View file

@ -1000,14 +1000,31 @@ class TestStartHotspot:
def test_writes_captive_portal_config_before_creating_hotspot(self, reset_runtime_config):
"""dnsmasq reads the include at activation, so it must exist before `nmcli ... hotspot`."""
include = captive_portal.INCLUDE_FILE
result, run = self._start_with_nmcli()
seen = {}
results = iter([
mock.Mock(returncode=0, stdout="", stderr=""), # radio on
mock.Mock(returncode=0, stdout="wlan0:disconnected\n", stderr=""), # device ready
mock.Mock(returncode=0, stdout="", stderr=""), # nmcli device wifi hotspot
mock.Mock(returncode=0, stdout="", stderr=""), # modify
mock.Mock(returncode=0, stdout="", stderr=""), # up
mock.Mock(returncode=0, stdout=HOTSPOT_IP_JSON, stderr=""), # ip addr
])
def run(cmd, **kwargs):
if 'hotspot' in cmd:
# Observe the include at the moment NetworkManager (and its dnsmasq) start.
seen['include_at_create'] = include.read_text() if include.exists() else None
return next(results)
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False), \
mock.patch("controller.lib.captive_portal.is_docker_mode", return_value=False), \
mock.patch("subprocess.run", side_effect=run), \
mock.patch("time.sleep"):
result = start_hotspot()
assert result["success"] is True
assert include.exists()
assert 'address=/captive.apple.com/10.42.0.1' in include.read_text()
# The address is only read after the hotspot exists; the include was written before that.
hotspot_call_index = next(i for i, c in enumerate(run.call_args_list) if 'hotspot' in c[0][0])
ip_call_index = next(i for i, c in enumerate(run.call_args_list) if c[0][0][0] == 'ip')
assert hotspot_call_index < ip_call_index
assert seen['include_at_create'] is not None
assert 'address=/captive.apple.com/10.42.0.1' in seen['include_at_create']
def test_disabled_removes_captive_portal_config(self, reset_runtime_config):
include = captive_portal.INCLUDE_FILE
@ -1029,6 +1046,49 @@ class TestStartHotspot:
ups = [c for c in run.call_args_list if c[0][0][:3] == ['nmcli', 'connection', 'up']]
assert len(ups) == 2
def test_reactivation_failure_is_logged(self, reset_runtime_config, caplog):
"""dnsmasq keeps the old address if the corrective `up` fails; say so."""
other = '[{"ifname": "wlan0", "addr_info": [{"family": "inet", "local": "10.42.1.1"}]}]'
ok = mock.Mock(returncode=0, stdout="", stderr="")
device_ready = mock.Mock(returncode=0, stdout="wlan0:disconnected\n", stderr="")
ip_addr = mock.Mock(returncode=0, stdout=other, stderr="")
failed_up = mock.Mock(returncode=4, stdout="", stderr="Error: Connection activation failed")
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False), \
mock.patch("controller.lib.captive_portal.is_docker_mode", return_value=False), \
mock.patch("subprocess.run", side_effect=[ok, device_ready, ok, ok, ok, ip_addr, failed_up]), \
mock.patch("time.sleep"):
result = start_hotspot()
assert result["success"] is True
assert "Could not re-activate hotspot for captive portal" in caplog.text
assert "Connection activation failed" in caplog.text
def test_wpa3_reverted_hotspot_still_gets_captive_portal_ip(self, reset_runtime_config):
"""A WPA3 failure that reverts to WPA2 leaves the hotspot up; it still needs the right address."""
other = '[{"ifname": "wlan0", "addr_info": [{"family": "inet", "local": "10.42.1.1"}]}]'
ok = mock.Mock(returncode=0, stdout="", stderr="")
device_ready = mock.Mock(returncode=0, stdout="wlan0:disconnected\n", stderr="")
sae_failed = mock.Mock(returncode=1, stdout="", stderr="Error: sae unsupported")
ip_addr = mock.Mock(returncode=0, stdout=other, stderr="")
def mock_get_config(key, default=None):
return {'hotspot.protocol': 'wpa3'}.get(key, default)
with mock.patch("controller.lib.admin.is_docker_mode", return_value=False), \
mock.patch("controller.lib.captive_portal.is_docker_mode", return_value=False), \
mock.patch("controller.lib.admin.get_config_value", side_effect=mock_get_config), \
mock.patch("subprocess.run", side_effect=[
ok, device_ready, ok, # radio, ready, hotspot
sae_failed, # modify to sae fails
ok, ok, # revert modify, revert up
ip_addr, ok, # captive portal: read address, re-activate
]) as run, \
mock.patch("time.sleep"):
result = start_hotspot()
assert result["success"] is False
assert "reverted to WPA2" in result["error"]
assert 'address=/captive.apple.com/10.42.1.1' in captive_portal.INCLUDE_FILE.read_text()
assert run.call_args_list[-1][0][0] == ["nmcli", "connection", "up", "Hotspot"]
def test_no_reactivation_when_ip_matches(self, reset_runtime_config):
result, run = self._start_with_nmcli()
ups = [c for c in run.call_args_list if c[0][0][:3] == ['nmcli', 'connection', 'up']]