From ea001751cb1393c1990392859376b2ecf1363203 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 12 Nov 2026 22:25:56 +0100 Subject: [PATCH 1/2] fix(vlans): set_vlan and set_interface refuse values with line breaks (#17) The VLAN name went into `name ""`, a port's description into `description `, each one line of a block sent line by line in config mode and then saved: a line break ended the line and the switch ran the rest as commands, a double quote ended the VLAN name. netOrk replays VLAN names other devices reported here (NetOrk/netork#2455). set_vlan() now raises ValueError for a name containing \r, \n or ", set_interface() for a description containing \r or \n, before anything is sent. --- CHANGELOG.md | 5 ++ napalm_tplink_jetstream/tplink_jetstream.py | 31 +++++++++- tests/unit/test_cli_values.py | 66 +++++++++++++++++++++ 3 files changed, 100 insertions(+), 2 deletions(-) create mode 100644 tests/unit/test_cli_values.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 42424fd..2eba6e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,11 @@ All notable changes to this driver. The format follows sent again. `get_ntp_servers()` lists the same servers. ### Fixed +- `set_vlan()` refuses a name with a line break or a double quote, `set_interface()` a + description with a line break (`ValueError`), before anything is sent + (#17, NetOrk/netork#2455). Sent line by line in config mode, a line break ended the + `name ""` or `description ` line and the switch ran the rest as commands, + then saved them. - `get_snmp_information()` reads each community from the table's `Name` column and its access from the `Type` column (#14). It took the `Index` column as the community, so the switch's `public` was reported as `1`, and read the access from the name, so every diff --git a/napalm_tplink_jetstream/tplink_jetstream.py b/napalm_tplink_jetstream/tplink_jetstream.py index 96968ea..7c4f42c 100644 --- a/napalm_tplink_jetstream/tplink_jetstream.py +++ b/napalm_tplink_jetstream/tplink_jetstream.py @@ -20,6 +20,7 @@ from __future__ import annotations import logging import re +from collections.abc import Mapping from typing import Any, ClassVar import napalm.base.constants as C @@ -47,6 +48,24 @@ logger = logging.getLogger(__name__) #: get_users' password field: the switch never shows a password, so it stays empty. _PASSWORD_NOT_SHOWN = "" # nosec B105 +#: What ends a CLI value early: a line break ends its line, a double quote a quoted value. +_LINE_BREAK = re.compile(r"[\r\n]") +_BREAKS_QUOTED_VALUE = re.compile(r'[\r\n"]') + + +def _check_cli_values(config: Mapping[str, Any]) -> None: + """Refuse a VLAN name or a description that would break out of its CLI line. + + Sent line by line in config mode, a line break ran the rest as commands of + their own; a double quote ended the quoted VLAN name (NetOrk/netork#2455). + """ + name = config.get("name") + if isinstance(name, str) and _BREAKS_QUOTED_VALUE.search(name): + raise ValueError(f"VLAN name {name!r} must be one line without double quotes") + description = config.get("description") + if isinstance(description, str) and _LINE_BREAK.search(description): + raise ValueError(f"description {description!r} must be one line") + class TPLinkJetstreamDriver( JetstreamTimeSyncMixin, ConfigLifecycleMixin, SnmpAgentMixin, SwitchDriver @@ -1569,7 +1588,11 @@ class TPLinkJetstreamDriver( # ------------------------------------------------------------------ def set_vlan(self, vlan_id: int, config: VlanConfigDict) -> None: - """Create or update a VLAN on the switch.""" + """Create or update a VLAN on the switch. + + A name with a line break or a double quote is refused before anything is sent. + """ + _check_cli_values(config) self._enter_config_mode() try: lines = [f"vlan {vlan_id}"] @@ -1585,7 +1608,11 @@ class TPLinkJetstreamDriver( self._save_config() def set_interface(self, interface: str, config: InterfaceConfigDict) -> None: - """Configure a switch interface (mode, VLAN membership, admin state).""" + """Configure a switch interface (mode, VLAN membership, admin state). + + A description with a line break is refused before anything is sent. + """ + _check_cli_values(config) mode = config.get("mode") iface = self._to_cli_interface(interface) diff --git a/tests/unit/test_cli_values.py b/tests/unit/test_cli_values.py new file mode 100644 index 0000000..83373f2 --- /dev/null +++ b/tests/unit/test_cli_values.py @@ -0,0 +1,66 @@ +"""set_vlan and set_interface refuse values that break out of their CLI line +(NetOrk/netork#2455). + +The VLAN name goes into ``name ""`` and a port's description into +``description ``, each one line of a block sent line by line in config +mode. A line break in either ended that line and sent the rest to the switch as +commands of its own, before ``copy running-config startup-config``; a double +quote ended the VLAN name. Such a value is refused before anything is sent. +""" + +from __future__ import annotations + +from unittest.mock import MagicMock + +import pytest + +from napalm_tplink_jetstream.tplink_jetstream import TPLinkJetstreamDriver + +#: The name from the security report: a quote ends the name, a line break the line. +INJECTED = 'guest"\nuser name x privilege admin password y\nexit\nvlan 42\n name "guest' + + +@pytest.fixture +def driver(): + d = TPLinkJetstreamDriver("10.0.0.1", "admin", "pw") + d.device = MagicMock() + d.applied: list[str] = [] + d._enter_config_mode = MagicMock() + d._exit_config_mode = MagicMock() + d._save_config = MagicMock() + d._apply_config_lines = lambda text: d.applied.append(text) or [] + return d + + +def _nothing_sent(driver) -> None: + assert driver.applied == [] + driver._enter_config_mode.assert_not_called() + driver._save_config.assert_not_called() + + +@pytest.mark.parametrize("name", [INJECTED, "a\nb", "a\rb", 'say "hi"']) +def test_a_vlan_name_with_a_line_break_or_a_double_quote_is_refused(driver, name): + with pytest.raises(ValueError, match="VLAN name"): + driver.set_vlan(42, {"name": name}) + + _nothing_sent(driver) + + +def test_a_plain_vlan_name_is_sent_quoted(driver): + driver.set_vlan(42, {"name": "guest wifi"}) + + assert driver.applied == ['vlan 42\n name "guest wifi"\nexit'] + + +@pytest.mark.parametrize("description", ["uplink\nuser name x password y", "a\rb"]) +def test_a_description_with_a_line_break_is_refused(driver, description): + with pytest.raises(ValueError, match="description"): + driver.set_interface("Gi1/0/1", {"description": description}) + + _nothing_sent(driver) + + +def test_a_one_line_description_is_sent(driver): + driver.set_interface("Gi1/0/1", {"description": "to core-sw"}) + + assert driver.applied == ["interface gigabitEthernet 1/0/1\n description to core-sw\nexit"] -- 2.54.0 From a689c50ee1a4aa8b50af71e73a0ba1fcf6b182ee Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Fri, 13 Nov 2026 08:59:30 +0100 Subject: [PATCH 2/2] refactor: CLI value checks in their own module, uptime parser in parsers.py (#17) The checks against line breaks and double quotes made the driver module 27 lines longer than the quality ratchet allows (2014, recorded 1987) and set_interface 53 lines long (limit 50). The checks move to cli_values.py (check_cli_values); the uptime parser, a pure parser without the driver, moves to parsers.py as parse_uptime_seconds and reads its four units in one loop; set_vlan and set_interface say in one docstring line what they refuse. Behaviour is unchanged; the uptime test gains a string without days and an empty one. The baseline is lowered to what is measured now (1971). --- napalm_tplink_jetstream/cli_values.py | 27 +++++++++ napalm_tplink_jetstream/parsers.py | 19 ++++++ napalm_tplink_jetstream/tplink_jetstream.py | 65 ++++----------------- tests/quality_baseline.json | 2 +- tests/unit/test_driver.py | 5 +- 5 files changed, 62 insertions(+), 56 deletions(-) create mode 100644 napalm_tplink_jetstream/cli_values.py diff --git a/napalm_tplink_jetstream/cli_values.py b/napalm_tplink_jetstream/cli_values.py new file mode 100644 index 0000000..769a28f --- /dev/null +++ b/napalm_tplink_jetstream/cli_values.py @@ -0,0 +1,27 @@ +"""Values the driver writes into a CLI line, checked before anything is sent. + +A VLAN name goes into ``name ""`` and a port's description into +``description ``, each one line of a block sent line by line in config +mode. A line break ran the rest as commands of their own; a double quote ended +the quoted VLAN name (NetOrk/netork#2455). +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from typing import Any + +#: What ends a CLI value early: a line break ends its line, a double quote a quoted value. +_LINE_BREAK = re.compile(r"[\r\n]") +_BREAKS_QUOTED_VALUE = re.compile(r'[\r\n"]') + + +def check_cli_values(config: Mapping[str, Any]) -> None: + """Refuse a VLAN name or a description that would break out of its CLI line.""" + name = config.get("name") + if isinstance(name, str) and _BREAKS_QUOTED_VALUE.search(name): + raise ValueError(f"VLAN name {name!r} must be one line without double quotes") + description = config.get("description") + if isinstance(description, str) and _LINE_BREAK.search(description): + raise ValueError(f"description {description!r} must be one line") diff --git a/napalm_tplink_jetstream/parsers.py b/napalm_tplink_jetstream/parsers.py index 46444b1..0221b0f 100644 --- a/napalm_tplink_jetstream/parsers.py +++ b/napalm_tplink_jetstream/parsers.py @@ -62,3 +62,22 @@ def parse_snmp_community_access(output: str) -> dict[str, str]: typ = row[kind].lower() if kind is not None and kind < len(row) else "" access[row[name]] = "rw" if "write" in typ else "ro" return access + + +#: The parts of a ``Running Time`` and their seconds: ``5 day(s) 2 hour(s) 35 min(s) 16 sec(s)``. +_UPTIME_UNITS = (("day", 86400), ("hour", 3600), ("min", 60), ("sec", 1)) + + +def parse_uptime_seconds(uptime_str: str) -> float: + """Convert a TP-Link uptime string to seconds; a missing part counts as 0. + + Expected formats: + ``5 day(s) 2 hour(s) 35 min(s) 16 sec(s)`` + ``0 day(s) 0 hour(s) 5 min(s) 3 sec(s)`` + """ + total = 0 + for unit, seconds in _UPTIME_UNITS: + match = re.search(rf"(\d+)\s+{unit}", uptime_str, re.I) + if match: + total += int(match.group(1)) * seconds + return float(total) diff --git a/napalm_tplink_jetstream/tplink_jetstream.py b/napalm_tplink_jetstream/tplink_jetstream.py index 7c4f42c..af52508 100644 --- a/napalm_tplink_jetstream/tplink_jetstream.py +++ b/napalm_tplink_jetstream/tplink_jetstream.py @@ -20,7 +20,6 @@ from __future__ import annotations import logging import re -from collections.abc import Mapping from typing import Any, ClassVar import napalm.base.constants as C @@ -40,7 +39,12 @@ from netmiko import ConnectHandler from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException from napalm_tplink_jetstream._ssh import netmiko_connect_args -from napalm_tplink_jetstream.parsers import parse_snmp_communities, parse_snmp_community_access +from napalm_tplink_jetstream.cli_values import check_cli_values +from napalm_tplink_jetstream.parsers import ( + parse_snmp_communities, + parse_snmp_community_access, + parse_uptime_seconds, +) from napalm_tplink_jetstream.time_sync import JetstreamTimeSyncMixin logger = logging.getLogger(__name__) @@ -48,24 +52,6 @@ logger = logging.getLogger(__name__) #: get_users' password field: the switch never shows a password, so it stays empty. _PASSWORD_NOT_SHOWN = "" # nosec B105 -#: What ends a CLI value early: a line break ends its line, a double quote a quoted value. -_LINE_BREAK = re.compile(r"[\r\n]") -_BREAKS_QUOTED_VALUE = re.compile(r'[\r\n"]') - - -def _check_cli_values(config: Mapping[str, Any]) -> None: - """Refuse a VLAN name or a description that would break out of its CLI line. - - Sent line by line in config mode, a line break ran the rest as commands of - their own; a double quote ended the quoted VLAN name (NetOrk/netork#2455). - """ - name = config.get("name") - if isinstance(name, str) and _BREAKS_QUOTED_VALUE.search(name): - raise ValueError(f"VLAN name {name!r} must be one line without double quotes") - description = config.get("description") - if isinstance(description, str) and _LINE_BREAK.search(description): - raise ValueError(f"description {description!r} must be one line") - class TPLinkJetstreamDriver( JetstreamTimeSyncMixin, ConfigLifecycleMixin, SnmpAgentMixin, SwitchDriver @@ -287,29 +273,6 @@ class TPLinkJetstreamDriver( return parts[1].strip() return "" - @staticmethod - def _parse_uptime_seconds(uptime_str: str) -> float: - """Convert a TP-Link uptime string to seconds. - - Expected formats: - ``5 day(s) 2 hour(s) 35 min(s) 16 sec(s)`` - ``0 day(s) 0 hour(s) 5 min(s) 3 sec(s)`` - """ - days = hours = minutes = seconds = 0 - match = re.search(r"(\d+)\s+day", uptime_str, re.I) - if match: - days = int(match.group(1)) - match = re.search(r"(\d+)\s+hour", uptime_str, re.I) - if match: - hours = int(match.group(1)) - match = re.search(r"(\d+)\s+min", uptime_str, re.I) - if match: - minutes = int(match.group(1)) - match = re.search(r"(\d+)\s+sec", uptime_str, re.I) - if match: - seconds = int(match.group(1)) - return float(days * 86400 + hours * 3600 + minutes * 60 + seconds) - # ------------------------------------------------------------------ # NAPALM getters # ------------------------------------------------------------------ @@ -349,7 +312,7 @@ class TPLinkJetstreamDriver( uptime_str = self._parse_key_value(sys_info, "Running Time") or self._parse_key_value( sys_info, "Run Time" ) - uptime = self._parse_uptime_seconds(uptime_str) + uptime = parse_uptime_seconds(uptime_str) serial_number = self._parse_key_value(sys_info, "Serial Number") or "" @@ -1588,11 +1551,8 @@ class TPLinkJetstreamDriver( # ------------------------------------------------------------------ def set_vlan(self, vlan_id: int, config: VlanConfigDict) -> None: - """Create or update a VLAN on the switch. - - A name with a line break or a double quote is refused before anything is sent. - """ - _check_cli_values(config) + """Create or update a VLAN; a name that breaks its CLI line is refused first.""" + check_cli_values(config) self._enter_config_mode() try: lines = [f"vlan {vlan_id}"] @@ -1608,11 +1568,8 @@ class TPLinkJetstreamDriver( self._save_config() def set_interface(self, interface: str, config: InterfaceConfigDict) -> None: - """Configure a switch interface (mode, VLAN membership, admin state). - - A description with a line break is refused before anything is sent. - """ - _check_cli_values(config) + """Configure a port (mode, VLANs, admin state); refuses a multi-line description.""" + check_cli_values(config) mode = config.get("mode") iface = self._to_cli_interface(interface) diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 4e0b135..92873f0 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -27,7 +27,7 @@ "napalm_tplink_jetstream.tplink_jetstream" ], "python_file_lines": { - "napalm_tplink_jetstream/tplink_jetstream.py": 1987 + "napalm_tplink_jetstream/tplink_jetstream.py": 1971 }, "untyped_public": [] } diff --git a/tests/unit/test_driver.py b/tests/unit/test_driver.py index 95d4b14..cc199cc 100644 --- a/tests/unit/test_driver.py +++ b/tests/unit/test_driver.py @@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patch import pytest +from napalm_tplink_jetstream.parsers import parse_uptime_seconds from napalm_tplink_jetstream.tplink_jetstream import TPLinkJetstreamDriver # --------------------------------------------------------------------------- @@ -276,10 +277,12 @@ class TestUptimeParser: ("0 day(s) 0 hour(s) 0 min(s) 0 sec(s)", 0), ("1 day(s) 0 hour(s) 0 min(s) 0 sec(s)", 86400), ("5 day(s) 2 hour(s) 35 min(s) 16 sec(s)", 5 * 86400 + 2 * 3600 + 35 * 60 + 16), + ("5 min(s) 3 sec(s)", 5 * 60 + 3), + ("", 0), ], ) def test_parse_uptime_seconds(self, uptime_str, expected): - result = TPLinkJetstreamDriver._parse_uptime_seconds(uptime_str) + result = parse_uptime_seconds(uptime_str) assert result == float(expected) -- 2.54.0