captive portal: let acknowledged clients finish so the OS offers "Done"

A phone's sign-in sheet only shows "Done" once the OS re-probes and gets
the genuine success reply.  The Controller now remembers each client (by
hotspot IP) that has loaded the portal page and answers its later probes
with the reply each OS expects (Apple "Success" HTML, Android 204, Windows
"Microsoft Connect Test", ...).  The set is cleared when the hotspot
starts so a new session shows the page again.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-09-13 19:48:13 -06:00
parent 66151df6c6
commit f182e64e17
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
7 changed files with 108 additions and 15 deletions

View file

@ -9,15 +9,18 @@ import logging
from pathlib import Path
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi.responses import RedirectResponse, Response
from fastapi.templating import Jinja2Templates
from controller.lib.admin import get_hotspot_device, get_hotspot_ssid
from controller.lib.captive_portal import (
PORTAL_PATH,
PROBE_PATHS,
PROBE_SUCCESS_RESPONSES,
acknowledge_client,
get_hotspot_ip,
is_captive_portal_enabled,
is_client_acknowledged,
)
from controller.lib.config import is_docker_mode
@ -40,14 +43,22 @@ async def portal(request: Request):
if not ip:
# Hotspot is down; a page with the wrong address is worse than none.
raise HTTPException(status_code=404)
# The phone has seen the address; let its next probe succeed so it offers "Done".
acknowledge_client(request.client.host if request.client else None)
context = {"ip": ip, "ssid": get_hotspot_ssid()}
return templates.TemplateResponse(request, "portal.html", context, headers=NO_STORE)
async def probe():
"""A connectivity probe. Anything but the expected reply makes the phone show the portal."""
async def probe(request: Request):
"""
A connectivity probe. Anything but the expected reply makes the phone show the portal, so
redirect until this client has loaded the portal page, then give the reply it expects.
"""
if not is_captive_portal_enabled():
raise HTTPException(status_code=404)
if is_client_acknowledged(request.client.host if request.client else None):
status, media_type, body = PROBE_SUCCESS_RESPONSES[request.url.path]
return Response(content=body, status_code=status, media_type=media_type, headers=NO_STORE)
return RedirectResponse(url=PORTAL_PATH, status_code=302, headers=NO_STORE)

View file

@ -63,6 +63,8 @@ def _isolate_dnsmasq_include(tmp_path_factory, monkeypatch):
import controller.lib.captive_portal as captive_portal
include = tmp_path_factory.mktemp("dnsmasq") / "50-wrolpi-captive-portal.conf"
monkeypatch.setattr(captive_portal, "INCLUDE_FILE", include)
# Portal acknowledgements are process state; every test starts with none.
captive_portal.reset_acknowledged_clients()
@pytest.fixture(autouse=True)

View file

@ -470,7 +470,9 @@ def start_hotspot() -> dict:
# must be in place first. The address is not known until then; NetworkManager almost
# always picks the default, and the file is corrected below if it did not.
captive_portal_lib.apply_dnsmasq_config(captive_portal_lib.dnsmasq_config_ip()
or captive_portal_lib.DEFAULT_HOTSPOT_IP)
or captive_portal_lib.DEFAULT_HOTSPOT_IP)
# A new hotspot session: every client sees the portal page again.
captive_portal_lib.reset_acknowledged_clients()
# Create hotspot using NetworkManager
logger.info("Starting hotspot on %s with SSID %s", device, ssid)

View file

@ -26,17 +26,22 @@ PROBE_HOSTS = (
'nmcheck.gnome.org', # GNOME
)
# Paths those probes request. The Controller redirects each of these to the portal.
# Paths those probes request, and the reply each OS takes as "online". The Controller redirects a
# probe to the portal until the client has loaded the portal page, then returns the expected
# reply so the OS shows its "Done" button and keeps using the hotspot.
# `/` is not listed: the dashboard already answers it with HTML, which a probe treats as a portal.
PROBE_PATHS = (
'/hotspot-detect.html', # Apple
'/generate_204', # Android
'/connecttest.txt', # Windows 10+
'/ncsi.txt', # Windows 7/8
'/success.txt', # Firefox
'/canonical.html', # Firefox
'/check_network_status.txt', # GNOME
)
PROBE_SUCCESS_RESPONSES = {
'/hotspot-detect.html': (200, 'text/html', # Apple
'<HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY>Success</BODY></HTML>'),
'/generate_204': (204, 'text/plain', ''), # Android
'/connecttest.txt': (200, 'text/plain', 'Microsoft Connect Test'), # Windows 10+
'/ncsi.txt': (200, 'text/plain', 'Microsoft NCSI'), # Windows 7/8
'/success.txt': (200, 'text/plain', 'success\n'), # Firefox
'/canonical.html': (200, 'text/html', # Firefox
'<meta http-equiv="refresh" content="0;url=https://support.mozilla.org/kb/captive-portal"/>'),
'/check_network_status.txt': (200, 'text/plain', 'NetworkManager is online\n'), # GNOME
}
PROBE_PATHS = tuple(PROBE_SUCCESS_RESPONSES)
# `http://wrolpi/` also reaches the WROLPi from a hotspot client.
FRIENDLY_NAME = 'wrolpi'
@ -128,3 +133,22 @@ def dnsmasq_config_ip() -> Optional[str]:
except OSError:
pass
return None
# Clients (by hotspot IP) which have loaded the portal page. Their later probes get the success
# reply. Reset whenever the hotspot starts so a new session shows the page again.
_acknowledged_clients: set[str] = set()
def acknowledge_client(ip: str):
"""The client at `ip` has seen the portal page; its probes now say "online"."""
if ip:
_acknowledged_clients.add(ip)
def is_client_acknowledged(ip: str) -> bool:
return ip in _acknowledged_clients
def reset_acknowledged_clients():
_acknowledged_clients.clear()

View file

@ -59,7 +59,7 @@
<a class="btn secondary" href="https://{{ ip }}/controller/">Open the Controller</a>
<div class="note muted">
<p>If these buttons do nothing, close this window and open your browser to
<p>Tap <strong>Done</strong> to stay connected, then open your browser to
<strong>https://{{ ip }}</strong>.</p>
<p>Your browser will warn about the certificate the first time. That is expected for an
offline WROLPi; continue to the site.</p>

View file

@ -1089,6 +1089,13 @@ class TestStartHotspot:
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_start_forgets_acknowledged_clients(self, reset_runtime_config):
"""A new hotspot session shows every device the portal page again."""
captive_portal.acknowledge_client('10.42.0.210')
result, _ = self._start_with_nmcli()
assert result["success"] is True
assert not captive_portal.is_client_acknowledged('10.42.0.210')
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']]

View file

@ -13,7 +13,11 @@ from controller.lib.captive_portal import (
FRIENDLY_NAME,
PROBE_HOSTS,
PROBE_PATHS,
PROBE_SUCCESS_RESPONSES,
acknowledge_client,
apply_dnsmasq_config,
is_client_acknowledged,
reset_acknowledged_clients,
dnsmasq_config_ip,
get_hotspot_ip,
is_captive_portal_enabled,
@ -164,6 +168,49 @@ class TestProbeRedirects:
assert response.status_code == 404
class TestAcknowledgedClients:
"""Once a client has seen the portal page, its probes say "online" so the OS offers Done."""
@pytest.mark.parametrize("path", PROBE_PATHS)
def test_probe_succeeds_after_portal_seen(self, test_client, path):
with mock.patch("controller.api.captive_portal.get_hotspot_ip", return_value='10.42.0.1'):
assert test_client.get('/portal').status_code == 200
response = test_client.get(path, follow_redirects=False)
status, media_type, body = PROBE_SUCCESS_RESPONSES[path]
assert response.status_code == status
assert response.text == body
assert response.headers['cache-control'] == 'no-store'
if body:
assert response.headers['content-type'].startswith(media_type)
def test_apple_probe_says_success(self, test_client):
"""iOS looks for this exact body before it shows the Done button."""
acknowledge_client('testclient')
response = test_client.get('/hotspot-detect.html')
assert response.status_code == 200
assert '<BODY>Success</BODY>' in response.text
def test_portal_404_does_not_acknowledge(self, test_client):
"""A hotspot-down 404 is not the client seeing the address."""
with mock.patch("controller.api.captive_portal.get_hotspot_ip", return_value=None):
assert test_client.get('/portal').status_code == 404
assert test_client.get('/generate_204', follow_redirects=False).status_code == 302
def test_other_clients_still_redirected(self, test_client):
acknowledge_client('10.42.0.99')
assert not is_client_acknowledged('testclient')
assert test_client.get('/generate_204', follow_redirects=False).status_code == 302
def test_reset_shows_portal_again(self, test_client):
acknowledge_client('testclient')
reset_acknowledged_clients()
assert test_client.get('/generate_204', follow_redirects=False).status_code == 302
def test_acknowledge_ignores_missing_ip(self):
acknowledge_client(None)
assert not is_client_acknowledged(None)
class TestPortalPage:
def test_shows_address_and_links(self, test_client):