diff --git a/controller/api/captive_portal.py b/controller/api/captive_portal.py index 2f161379..fd4cf8e2 100644 --- a/controller/api/captive_portal.py +++ b/controller/api/captive_portal.py @@ -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) diff --git a/controller/conftest.py b/controller/conftest.py index 283766b1..c357188b 100644 --- a/controller/conftest.py +++ b/controller/conftest.py @@ -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) diff --git a/controller/lib/admin.py b/controller/lib/admin.py index 6a85b924..c2056b65 100644 --- a/controller/lib/admin.py +++ b/controller/lib/admin.py @@ -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) diff --git a/controller/lib/captive_portal.py b/controller/lib/captive_portal.py index 285ac8f5..6f3fe1d7 100644 --- a/controller/lib/captive_portal.py +++ b/controller/lib/captive_portal.py @@ -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 + '
If these buttons do nothing, close this window and open your browser to +
Tap Done to stay connected, then open your browser to https://{{ ip }}.
Your browser will warn about the certificate the first time. That is expected for an offline WROLPi; continue to the site.
diff --git a/controller/test/test_admin.py b/controller/test/test_admin.py index 14f6a490..6d58289f 100644 --- a/controller/test/test_admin.py +++ b/controller/test/test_admin.py @@ -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']] diff --git a/controller/test/test_captive_portal.py b/controller/test/test_captive_portal.py index 46e2ae5b..a001bfea 100644 --- a/controller/test/test_captive_portal.py +++ b/controller/test/test_captive_portal.py @@ -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 'Success' 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):