"""A DAL GET is read the way the gateway sends it: sealed, with its data under ``Object`` (#25). ``_read_dal_or_page`` parsed the answer to ``GET /cgi-bin/DAL?oid=...`` as it came, but the gateway seals it (``{"content", "iv"}``) like the answer to a PUT. The parsers found none of their keys in the envelope and reported no hosts, ARP entries, port forwards, SSIDs, radios or Wi-Fi clients, and since nothing raised, the HTML fallback never ran either. Decrypted, the answer is ``{"result": "ZCFG_SUCCESS", "Object": [...]}``. The host list is the one the gateway's own web interface reads, ``oid=lanhosts``: the driver asked for ``LAN_HOSTS``, a name the gateway does not know and answers, like any unknown name, with an empty ``Object``. Port forwards are ``oid=nat`` (the driver asked for ``NAT_PORTMAP``). """ from __future__ import annotations import copy import json from typing import Any import pytest import requests from napalm.base.exceptions import ConnectionException from tests.gateway import dal, driver, fixture, requested, response LANHOSTS = fixture("lanhosts") def _with_host(**changes: Any) -> dict[str, Any]: """The recorded host list, its first host changed by *changes*.""" answer = copy.deepcopy(LANHOSTS) answer["Object"][0]["lanhosts"][0].update(changes) return answer #: A port forward as the gateway's web interface edits it (the rule object its NAT #: page sends to ``oid=nat``). The recorded gateway is a bridge and has none, so the #: values are placeholders; the field names are the gateway's. RULE: dict[str, Any] = { "Index": 1, "Enable": True, "Protocol": "TCP", "Description": "web", "Interface": "IP.Interface.3", "ExternalPortStart": 8443, "ExternalPortEnd": 8443, "InternalPortStart": 443, "InternalPortEnd": 443, "InternalClient": "192.0.2.3", "SetOriginatingIP": False, "OriginatingIpAddress": "", "OriginatingSubnetMask": "255.255.255.255", "WANIP": "", "X_ZYXEL_AutoDetectWanStatus": False, } def _nat(*rules: dict[str, Any]) -> dict[str, Any]: return {**fixture("nat"), "Object": list(rules)} # --- the sealed answer ------------------------------------------------------------------ def test_the_sealed_host_list_is_decrypted_and_read(): hosts = driver({dal("lanhosts"): LANHOSTS}).get_hosts() assert [(h["mac"], h["ip"]) for h in hosts] == [ ("02:00:00:00:00:02", "192.0.2.2"), ("02:00:00:00:00:03", "192.0.2.3"), ] def test_the_host_list_is_the_one_the_web_interface_reads(): drv = driver({dal("lanhosts"): LANHOSTS}) drv.get_hosts() assert requested(drv) == ["http://192.0.2.1:80/cgi-bin/DAL?oid=lanhosts"] def test_an_unsealed_answer_is_read_as_it_is(): hosts = driver({dal("lanhosts"): response(200, json.dumps(LANHOSTS))}).get_hosts() assert len(hosts) == 2 def test_an_answer_the_gateway_refused_falls_back_to_the_page(): refused = {"result": "ZCFG_NO_SUCH_OBJECT", "Object": []} page = response(200, "192.0.2.4 02:00:00:00:00:04 tablet") hosts = driver({dal("lanhosts"): refused, "dhcp.htm": page}).get_hosts() assert [h["ip"] for h in hosts] == ["192.0.2.4"] def test_an_answer_that_cannot_be_decrypted_falls_back_to_the_page(): garbled = response( 200, json.dumps({"content": "bm90IHNlYWxlZA==", "iv": "AAAAAAAAAAAAAAAAAAAAAA=="}) ) page = response(200, "192.0.2.4 02:00:00:00:00:04 tablet") hosts = driver({dal("lanhosts"): garbled, "dhcp.htm": page}).get_hosts() assert [h["ip"] for h in hosts] == ["192.0.2.4"] def test_a_gateway_with_no_hosts_has_none(): empty = copy.deepcopy(LANHOSTS) empty["Object"][0]["lanhosts"] = [] assert driver({dal("lanhosts"): empty}).get_hosts() == [] # --- the hosts -------------------------------------------------------------------------- def test_a_recorded_host_reads_as_it_is_on_the_gateway(): host = driver({dal("lanhosts"): LANHOSTS}).get_hosts()[0] assert host == { "mac": "02:00:00:00:00:02", "ip": "192.0.2.2", "hostname": "", # the gateway says "Unknown" "interface_type": "LAN", "is_active": True, } def test_a_host_name_the_gateway_knows_is_reported(): hosts = driver({dal("lanhosts"): _with_host(HostName="printer")}).get_hosts() assert hosts[0]["hostname"] == "printer" def test_a_wifi_host_is_on_the_wlan(): answer = _with_host(X_ZYXEL_ConnectionType="Wi-Fi 2.4GHz") assert driver({dal("lanhosts"): answer}).get_hosts()[0]["interface_type"] == "WLAN" def test_only_a_dhcp_host_has_a_lease(): answer = _with_host(AddressSource="DHCP", LeaseTimeRemaining=3600) hosts = driver({dal("lanhosts"): answer}).get_hosts() assert hosts[0]["lease_time_remaining"] == 3600 assert "lease_time_remaining" not in hosts[1] # AddressSource "Static" def test_an_inactive_host_is_reported_inactive(): hosts = driver({dal("lanhosts"): _with_host(Active=False)}).get_hosts() assert hosts[0]["is_active"] is False def test_the_arp_table_holds_the_active_hosts(): drv = driver({dal("lanhosts"): _with_host(Active=False)}) assert drv.get_arp_table() == [ {"interface": "LAN", "mac": "02:00:00:00:00:03", "ip": "192.0.2.3", "age": -1.0} ] # --- port forwards ---------------------------------------------------------------------- def test_the_recorded_bridge_has_no_port_forwards(): assert driver({dal("nat"): fixture("nat")}).get_port_forwards() == [] def test_a_port_forward_reads_as_the_gateway_lists_it(): forwards = driver({dal("nat"): _nat(RULE)}).get_port_forwards() assert forwards == [ { "name": "web", "protocol": "TCP", "external_port": 8443, "internal_ip": "192.0.2.3", "internal_port": 443, "enabled": True, } ] def test_a_forward_for_tcp_and_udp_is_one_per_protocol(): forwards = driver({dal("nat"): _nat({**RULE, "Protocol": "ALL"})}).get_port_forwards() assert [f["protocol"] for f in forwards] == ["TCP", "UDP"] def test_a_disabled_forward_is_reported_disabled(): forwards = driver({dal("nat"): _nat({**RULE, "Enable": False})}).get_port_forwards() assert forwards[0]["enabled"] is False def test_a_forward_limited_to_one_source_names_it(): rule = {**RULE, "SetOriginatingIP": True, "OriginatingIpAddress": "198.51.100.7"} forwards = driver({dal("nat"): _nat(rule)}).get_port_forwards() assert forwards[0]["remote_host"] == "198.51.100.7" def test_port_forwards_are_read_from_the_nat_oid(): drv = driver({dal("nat"): fixture("nat")}) drv.get_port_forwards() assert requested(drv) == ["http://192.0.2.1:80/cgi-bin/DAL?oid=nat"] # --- Wi-Fi ------------------------------------------------------------------------------ @pytest.mark.parametrize( ("getter", "oid", "empty"), [ ("get_wireless_clients", "WIFI_CLIENTS", []), ("get_ssids", "WIFI_SSIDS", {}), ("get_radio_status", "WIFI_RADIO", {}), ], ) def test_a_sealed_wifi_answer_is_decrypted(getter, oid, empty): """The recorded gateway has no Wi-Fi: it answers these with an empty ``Object``.""" assert getattr(driver({dal(oid): fixture("LAN_HOSTS")}), getter)() == empty def test_a_wifi_answer_without_object_falls_back_to_the_page(): answer = {"result": "ZCFG_SUCCESS"} drv = driver({dal("WIFI_SSIDS"): answer, "wireless.htm": response(200, "")}) drv.get_ssids() assert requested(drv)[-1].endswith("/wireless.htm") def test_a_wifi_client_under_object_is_read(): """Not recorded: the field names are the parser's, not yet checked against a gateway.""" client = {"MACAddress": "02:00:00:00:00:05", "SSID": "guest", "Signal": -61} answer = {"result": "ZCFG_SUCCESS", "Object": [client]} clients = driver({dal("WIFI_CLIENTS"): answer}).get_wireless_clients() assert [(c["mac"], c["signal"]) for c in clients] == [("02:00:00:00:00:05", -61)] def test_a_failed_request_still_raises(): drv = driver({dal("lanhosts"): requests.Response()}) drv._session.get.side_effect = requests.ConnectTimeout("timed out") # type: ignore[union-attr] with pytest.raises(ConnectionException, match="timed out"): drv.get_hosts()