mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-03 13:19:58 -05:00
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:
parent
6bea09600e
commit
85c27b91df
6 changed files with 118 additions and 28 deletions
|
|
@ -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")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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']]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue