"""A logged-in driver whose gateway answers GETs from recorded fixtures, sealed. The fixtures in ``fixtures/`` are a VMG4005-B50A's (firmware V5.17(ABQA.3.1)C0) answers, anonymised: addresses under 192.0.2.0/24, MAC addresses replaced by placeholders, the serial number replaced, the provisioning key and PLOAM password emptied. The gateway seals a DAL answer as ``{"content", "iv"}``; :func:`driver` seals each fixture with a real :class:`ZyxelCrypto` and the driver's own key, so what the driver reads has gone through the decryption. """ from __future__ import annotations import json from pathlib import Path from typing import Any from unittest.mock import MagicMock import requests from napalm_zyxel import ZyxelVMGDriver from napalm_zyxel.zyxel_driver import ZyxelCrypto FIXTURES = Path(__file__).parent / "fixtures" FIRMWARE = "vmg4005-b50a-ABQA.3.1" AES_KEY = bytes(range(32)) def fixture(name: str) -> Any: """The recorded answer *name* (``cardpage_status``, ``lanhosts``, ...).""" return json.loads((FIXTURES / f"{FIRMWARE}-{name}.json").read_text()) def dal(oid: str) -> str: """The path a DAL GET of *oid* is sent to.""" return f"cgi-bin/DAL?oid={oid}" def response(status: int, text: str = "") -> requests.Response: resp = requests.Response() resp.status_code = status resp._content = text.encode() resp.url = "http://192.0.2.1/" return resp def _crypto() -> ZyxelCrypto: crypto = ZyxelCrypto() crypto.aes_key = AES_KEY return crypto def sealed(answer: Any) -> requests.Response: """*answer* the way the gateway sends it: AES-encrypted, ``{"content", "iv"}``.""" envelope = _crypto().encrypt_json(answer) return response(200, json.dumps({"content": envelope["content"], "iv": envelope["iv"]})) def driver(answers: dict[str, Any]) -> ZyxelVMGDriver: """A logged-in driver whose gateway answers a GET of each path in *answers*: a response as it is, anything else sealed. Any other path answers 404.""" drv = ZyxelVMGDriver("192.0.2.1", "admin", "password") # NAPALM's __del__ asks is_alive(), which opens a TCP connection: not in a test. drv.is_alive = lambda: {"is_alive": False} # type: ignore[method-assign] def get(url: str, params: dict[str, Any] | None = None, **_: Any) -> requests.Response: for path, answer in answers.items(): if url.endswith(f"/{path}"): return answer if isinstance(answer, requests.Response) else sealed(answer) return response(404) session = MagicMock(spec=requests.Session) session.get.side_effect = get drv._session = session drv._sessionkey = "1" drv._crypto = _crypto() drv._device_info = fixture("getBasicInformation") return drv def requested(drv: ZyxelVMGDriver) -> list[str]: """The URLs the driver sent a GET to, in order.""" return [call.args[0] for call in drv._session.get.call_args_list] # type: ignore[union-attr]