network-sandbox-engine 2.1.1__tar.gz → 2.1.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/PKG-INFO +1 -1
  2. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/network_sandbox_engine.egg-info/PKG-INFO +1 -1
  3. network_sandbox_engine-2.1.2/nse/core/sniffer.py +96 -0
  4. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/pyproject.toml +1 -1
  5. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_engine_internals.py +126 -4
  6. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_paths.py +78 -8
  7. network_sandbox_engine-2.1.1/nse/core/sniffer.py +0 -57
  8. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/LICENSE +0 -0
  9. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/README.md +0 -0
  10. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/network_sandbox_engine.egg-info/SOURCES.txt +0 -0
  11. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/network_sandbox_engine.egg-info/dependency_links.txt +0 -0
  12. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/network_sandbox_engine.egg-info/entry_points.txt +0 -0
  13. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/network_sandbox_engine.egg-info/requires.txt +0 -0
  14. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/network_sandbox_engine.egg-info/top_level.txt +0 -0
  15. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/__init__.py +0 -0
  16. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/cli/__init__.py +0 -0
  17. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/cli/runner.py +0 -0
  18. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/__init__.py +0 -0
  19. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/mock_listener.py +0 -0
  20. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/naming.py +0 -0
  21. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/netns_controller.py +0 -0
  22. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/paths.py +0 -0
  23. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/pipeline.py +0 -0
  24. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/rule_engine.py +0 -0
  25. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/scapy_injector.py +0 -0
  26. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/trace_harvester.py +0 -0
  27. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/core/utils.py +0 -0
  28. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/models/__init__.py +0 -0
  29. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/models/test_request.py +0 -0
  30. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/nse/models/trace_event.py +0 -0
  31. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/setup.cfg +0 -0
  32. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_docs_examples.py +0 -0
  33. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_netns.py +0 -0
  34. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_oracle_e2e.py +0 -0
  35. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_pipeline_unit.py +0 -0
  36. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_runner_cli.py +0 -0
  37. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_runner_logic.py +0 -0
  38. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_trace_harvester.py +0 -0
  39. {network_sandbox_engine-2.1.1 → network_sandbox_engine-2.1.2}/tests/test_trace_parser.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: network-sandbox-engine
3
- Version: 2.1.1
3
+ Version: 2.1.2
4
4
  Summary: Headless Python engine for isolated network namespace testing and PCAP assertions.
5
5
  Author: onyks
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: network-sandbox-engine
3
- Version: 2.1.1
3
+ Version: 2.1.2
4
4
  Summary: Headless Python engine for isolated network namespace testing and PCAP assertions.
5
5
  Author: onyks
6
6
  License-Expression: MIT
@@ -0,0 +1,96 @@
1
+ # Copyright (c) 2026 onyks
2
+ # Licensed under the MIT License.
3
+
4
+ """
5
+ PCAPAsserter: packet sniffing assertion tool based on Scapy's AsyncSniffer.
6
+
7
+ Designed for automated headless pipeline testing to verify zero-leak policies.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import logging
14
+ from typing import TYPE_CHECKING
15
+
16
+ if TYPE_CHECKING:
17
+ from scapy.packet import Packet
18
+
19
+ logger = logging.getLogger("nse.core.sniffer")
20
+
21
+ #: ICMPv6 message types 133-137: Router Solicitation, Router Advertisement,
22
+ #: Neighbour Solicitation, Neighbour Advertisement and Redirect. All of them are
23
+ #: link-local by definition - they carry a hop limit of 255 and are discarded by
24
+ #: the first router - so none can reach a remote observer and none belongs in a
25
+ #: leak assertion.
26
+ ND_TYPE_MIN = 133
27
+ ND_TYPE_MAX = 137
28
+
29
+ #: Background chatter suppressed on every capture unless a caller opts out.
30
+ #:
31
+ #: This used to read ``not arp and not icmp6``, which was broader than the noise
32
+ #: it meant to describe. ICMPv6 is not only Neighbour Discovery: the expression
33
+ #: also discarded echo request/reply to a **globally routable** address, which is
34
+ #: cleartext traffic leaving the host - precisely what a class named for
35
+ #: "asserting that no traffic leaks outside sandbox boundaries" exists to catch.
36
+ #: Because the filter is compiled into BPF, those packets never reached
37
+ #: userspace, so no consumer could see or recover them.
38
+ #:
39
+ #: Narrowed to the ND types the comment always claimed. See
40
+ #: https://github.com/onyks-os/NetworkSandboxEngine/issues/14.
41
+ DEFAULT_FILTER = (
42
+ f"not arp and not (icmp6 and icmp6[icmp6type] >= {ND_TYPE_MIN} "
43
+ f"and icmp6[icmp6type] <= {ND_TYPE_MAX})"
44
+ )
45
+
46
+
47
+ class PCAPAsserter:
48
+ """
49
+ Asynchronous packet sniffer wrapper based on Scapy's AsyncSniffer.
50
+ Used for asserting that no traffic leaks outside sandbox boundaries.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ iface: str,
56
+ filter: str | None = None,
57
+ *,
58
+ replace_default_filter: bool = False,
59
+ ) -> None:
60
+ """
61
+ Arm a sniffer on *iface*.
62
+
63
+ *filter* is combined with :data:`DEFAULT_FILTER` unless
64
+ *replace_default_filter* is set, in which case it is used alone. The
65
+ override exists because the default is compiled into BPF and evaluated
66
+ in the kernel: a packet it excludes never reaches userspace, so a caller
67
+ that needs to assert on suppressed traffic cannot compensate downstream.
68
+ Combining is the safe default; replacing is the escape hatch.
69
+ """
70
+ from scapy.all import AsyncSniffer
71
+
72
+ self.iface = iface
73
+ if filter and replace_default_filter:
74
+ self.filter = filter
75
+ elif filter:
76
+ self.filter = f"({DEFAULT_FILTER}) and ({filter})"
77
+ else:
78
+ self.filter = DEFAULT_FILTER
79
+
80
+ self._sniffer = AsyncSniffer(iface=self.iface, filter=self.filter)
81
+
82
+ async def start(self) -> None:
83
+ """Start the async sniffer."""
84
+ logger.info(
85
+ "Starting PCAP sniffer on %s with BPF filter: %s",
86
+ self.iface,
87
+ self.filter,
88
+ )
89
+ self._sniffer.start()
90
+
91
+ async def stop(self) -> list[Packet]:
92
+ """Stop the async sniffer and return captured packets."""
93
+ logger.info("Stopping PCAP sniffer on %s", self.iface)
94
+ loop = asyncio.get_running_loop()
95
+ packets = await loop.run_in_executor(None, self._sniffer.stop)
96
+ return list(packets) if packets is not None else []
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
6
6
 
7
7
  [project]
8
8
  name = "network-sandbox-engine"
9
- version = "2.1.1"
9
+ version = "2.1.2"
10
10
  description = "Headless Python engine for isolated network namespace testing and PCAP assertions."
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.10"
@@ -668,19 +668,141 @@ def test_injector_wraps_scapy_failures() -> None:
668
668
 
669
669
 
670
670
  def test_pcap_asserter_combines_filters() -> None:
671
- from nse.core.sniffer import PCAPAsserter
671
+ from nse.core.sniffer import DEFAULT_FILTER, PCAPAsserter
672
672
 
673
673
  with patch("scapy.all.AsyncSniffer"):
674
674
  asserter = PCAPAsserter(iface="veth0", filter="port 53")
675
- assert asserter.filter == "(not arp and not icmp6) and (port 53)"
675
+ assert asserter.filter == f"({DEFAULT_FILTER}) and (port 53)"
676
676
 
677
677
 
678
678
  def test_pcap_asserter_default_filter() -> None:
679
- from nse.core.sniffer import PCAPAsserter
679
+ from nse.core.sniffer import DEFAULT_FILTER, PCAPAsserter
680
680
 
681
681
  with patch("scapy.all.AsyncSniffer"):
682
682
  asserter = PCAPAsserter(iface="veth0")
683
- assert asserter.filter == "not arp and not icmp6"
683
+ assert asserter.filter == DEFAULT_FILTER
684
+
685
+
686
+ def test_pcap_asserter_can_replace_the_default_filter() -> None:
687
+ """The default is compiled into BPF and evaluated in the kernel, so a packet
688
+ it excludes never reaches userspace. A caller that needs to assert on
689
+ suppressed traffic has to be able to opt out, not merely add to it."""
690
+ from nse.core.sniffer import PCAPAsserter
691
+
692
+ with patch("scapy.all.AsyncSniffer"):
693
+ asserter = PCAPAsserter(iface="veth0", filter="icmp6", replace_default_filter=True)
694
+ assert asserter.filter == "icmp6"
695
+
696
+
697
+ def test_replacing_the_default_without_a_filter_still_yields_the_default() -> None:
698
+ """`replace_default_filter=True` with nothing to replace it with must not
699
+ produce an empty filter, which libpcap reads as "capture everything"."""
700
+ from nse.core.sniffer import DEFAULT_FILTER, PCAPAsserter
701
+
702
+ with patch("scapy.all.AsyncSniffer"):
703
+ asserter = PCAPAsserter(iface="veth0", replace_default_filter=True)
704
+ assert asserter.filter == DEFAULT_FILTER
705
+
706
+
707
+ # ---------------------------------------------------------------------------
708
+ # What the default filter actually lets through
709
+ # ---------------------------------------------------------------------------
710
+ #
711
+ # The tests above assert on the filter *string*. These assert on its *effect*,
712
+ # by compiling it with libpcap and replaying packets through it from a pcap
713
+ # file - which needs no privileges and no interface. That distinction matters
714
+ # here: the bug this filter had was not a typo in the string, it was the string
715
+ # meaning more than its author intended.
716
+
717
+
718
+ def _survives_default_filter(packet: object) -> bool:
719
+ """True if *packet* would reach userspace through the default filter."""
720
+ import tempfile
721
+
722
+ from scapy.all import sniff, wrpcap
723
+
724
+ from nse.core.sniffer import DEFAULT_FILTER
725
+
726
+ with tempfile.NamedTemporaryFile(suffix=".pcap") as handle:
727
+ wrpcap(handle.name, [packet])
728
+ return len(sniff(offline=handle.name, filter=DEFAULT_FILTER)) > 0
729
+
730
+
731
+ def test_the_default_filter_compiles() -> None:
732
+ """A malformed BPF expression changes what is captured with no error at all,
733
+ which is the same class of failure as the one being fixed."""
734
+ from scapy.arch.common import compile_filter
735
+
736
+ from nse.core.sniffer import DEFAULT_FILTER
737
+
738
+ compile_filter(DEFAULT_FILTER, linktype=1) # DLT_EN10MB; raises on a bad expression
739
+
740
+
741
+ def test_an_icmpv6_echo_to_a_global_address_is_captured() -> None:
742
+ """The regression. `not icmp6` discarded this - a routable cleartext packet
743
+ leaving the host, which is exactly what a leak assertion must see."""
744
+ from scapy.all import Ether, IPv6
745
+ from scapy.layers.inet6 import ICMPv6EchoRequest
746
+
747
+ packet = Ether() / IPv6(dst="2001:4860:4860::8888") / ICMPv6EchoRequest()
748
+ assert _survives_default_filter(packet) is True
749
+
750
+
751
+ @pytest.mark.parametrize(
752
+ ("icmp6_type", "name"),
753
+ [
754
+ pytest.param(128, "echo request", id="128-echo-request"),
755
+ pytest.param(129, "echo reply", id="129-echo-reply"),
756
+ pytest.param(132, "just below the ND range", id="132-lower-boundary"),
757
+ pytest.param(138, "just above the ND range", id="138-upper-boundary"),
758
+ pytest.param(139, "node information query", id="139-node-info-query"),
759
+ ],
760
+ )
761
+ def test_routable_icmpv6_types_outside_the_nd_range_are_captured(
762
+ icmp6_type: int, name: str
763
+ ) -> None:
764
+ """Both ends of the suppressed range are pinned, not just the middle.
765
+
766
+ Widening the range in either direction re-creates the original defect for
767
+ whatever it swallows, and the ND-specific tests below would not notice:
768
+ they only prove the types inside the range stay out.
769
+ """
770
+ from scapy.all import Ether, IPv6, raw
771
+ from scapy.layers.inet6 import ICMPv6Unknown
772
+
773
+ packet = Ether() / IPv6(dst="2001:4860:4860::8888") / ICMPv6Unknown(type=icmp6_type)
774
+ assert raw(packet) # the packet is well-formed before we ask about the filter
775
+ assert _survives_default_filter(packet) is True, name
776
+
777
+
778
+ @pytest.mark.parametrize(
779
+ ("name", "layer_name"),
780
+ [
781
+ ("router advertisement", "ICMPv6ND_RA"),
782
+ ("neighbour solicitation", "ICMPv6ND_NS"),
783
+ ("neighbour advertisement", "ICMPv6ND_NA"),
784
+ ],
785
+ )
786
+ def test_neighbour_discovery_is_still_suppressed(name: str, layer_name: str) -> None:
787
+ """The noise the filter was always meant to drop keeps being dropped."""
788
+ import scapy.layers.inet6 as inet6
789
+ from scapy.all import Ether, IPv6
790
+
791
+ packet = Ether() / IPv6(dst="ff02::1") / getattr(inet6, layer_name)()
792
+ assert _survives_default_filter(packet) is False, name
793
+
794
+
795
+ def test_arp_is_still_suppressed() -> None:
796
+ from scapy.all import ARP, Ether
797
+
798
+ assert _survives_default_filter(Ether() / ARP()) is False
799
+
800
+
801
+ def test_ordinary_wan_traffic_is_captured() -> None:
802
+ """The control: a filter that drops everything would pass every test above."""
803
+ from scapy.all import IP, TCP, Ether
804
+
805
+ assert _survives_default_filter(Ether() / IP(dst="1.2.3.4") / TCP(dport=443)) is True
684
806
 
685
807
 
686
808
  # ---------------------------------------------------------------------------
@@ -19,6 +19,7 @@ from __future__ import annotations
19
19
  import os
20
20
  import stat
21
21
  import subprocess
22
+ import sys
22
23
  from pathlib import Path
23
24
  from unittest.mock import patch
24
25
 
@@ -249,24 +250,93 @@ def test_a_missing_binary_is_also_a_file_not_found_error() -> None:
249
250
  resolve("definitely-not-a-real-binary")
250
251
 
251
252
 
253
+ def _ruff(*args: str, cwd: Path) -> subprocess.CompletedProcess[str]:
254
+ """
255
+ Run the ruff that belongs to the interpreter running these tests.
256
+
257
+ A bare `"ruff"` argv resolves through $PATH, and `make setup` installs ruff
258
+ into the project virtualenv, which CI never puts on $PATH - so the guard
259
+ below raised FileNotFoundError on every runner while passing on a developer
260
+ machine that happened to have ruff installed globally.
261
+ """
262
+ return subprocess.run(
263
+ [sys.executable, "-m", "ruff", *args],
264
+ cwd=cwd,
265
+ capture_output=True,
266
+ text=True,
267
+ check=False,
268
+ )
269
+
270
+
271
+ def _skip_without_ruff(result: subprocess.CompletedProcess[str]) -> None:
272
+ if "No module named ruff" in result.stderr: # pragma: no cover - ruff installed
273
+ pytest.skip("ruff is not installed in this environment")
274
+
275
+
252
276
  def test_no_source_file_still_invokes_a_bare_binary() -> None:
253
277
  """
254
278
  The migration guard. `ruff --select S607` is the real check and it runs in
255
279
  `make lint`; this asserts it stays selected, because a rule silently dropped
256
280
  from the config is how 47 call sites came back.
281
+
282
+ Two ways this passed without checking anything, both fixed here:
283
+
284
+ - It linted `ttp/`, a package that belongs to a different repository. `ruff
285
+ check` on a path that does not exist warns on stderr, prints "All checks
286
+ passed!" and exits 0 - so the guard reported success while reading no
287
+ source at all. The directory is now asserted to exist, and a lint that
288
+ failed to open its target is a failure rather than a pass.
289
+ - It invoked a bare `"ruff"` and guarded on `returncode == 127`, a shell
290
+ convention `subprocess.run` never produces without a shell. ruff lives in
291
+ the project virtualenv, which CI does not put on $PATH, so the call raised
292
+ FileNotFoundError, the skip never ran, and the job went red. `_ruff` now
293
+ runs the ruff belonging to this interpreter.
257
294
  """
258
- result = subprocess.run(
259
- ["ruff", "check", "--select", "S607", "ttp/", "--output-format", "concise"],
260
- cwd=Path(__file__).resolve().parent.parent,
261
- capture_output=True,
262
- text=True,
263
- check=False,
295
+ package = Path(__file__).resolve().parent.parent / "nse"
296
+ assert package.is_dir(), f"{package} does not exist, so this guard would lint nothing"
297
+
298
+ result = _ruff(
299
+ "check", "--select", "S607", package.name, "--output-format", "concise", cwd=package.parent
264
300
  )
265
- if result.returncode == 127: # pragma: no cover - ruff not installed
266
- pytest.skip("ruff is not available")
301
+ _skip_without_ruff(result)
302
+
303
+ assert "Failed to lint" not in result.stderr, result.stderr
267
304
  assert result.returncode == 0, result.stdout
268
305
 
269
306
 
307
+ def test_the_s607_guard_would_report_a_bare_binary(tmp_path: Path) -> None:
308
+ """
309
+ The positive control for the guard above.
310
+
311
+ "All checks passed!" means nothing unless the rule would have said otherwise,
312
+ and the rule can stop firing without anyone noticing: dropped from `select`,
313
+ silenced by a broadened `ignore`, or renamed upstream. This feeds ruff a call
314
+ site of exactly the shape the migration removed and asserts it is reported.
315
+ """
316
+ offender = tmp_path / "offender.py"
317
+ offender.write_text("import subprocess\n\nsubprocess.run(['ip', 'link'], check=False)\n")
318
+
319
+ # --isolated so the repository's own ruff configuration cannot decide the
320
+ # outcome of its own positive control.
321
+ result = _ruff(
322
+ "check",
323
+ "--select",
324
+ "S607",
325
+ "--isolated",
326
+ "--no-cache",
327
+ offender.name,
328
+ "--output-format",
329
+ "concise",
330
+ cwd=tmp_path,
331
+ )
332
+ _skip_without_ruff(result)
333
+
334
+ assert "S607" in result.stdout, (
335
+ f"S607 did not fire on a bare-binary call, so the guard above cannot fail: "
336
+ f"{result.stdout!r} {result.stderr!r}"
337
+ )
338
+
339
+
270
340
  # ---------------------------------------------------------------------------
271
341
  # Graceful degradation on a host that lacks an optional tool
272
342
  # ---------------------------------------------------------------------------
@@ -1,57 +0,0 @@
1
- # Copyright (c) 2026 onyks
2
- # Licensed under the MIT License.
3
-
4
- """
5
- PCAPAsserter: packet sniffing assertion tool based on Scapy's AsyncSniffer.
6
-
7
- Designed for automated headless pipeline testing to verify zero-leak policies.
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import asyncio
13
- import logging
14
- from typing import TYPE_CHECKING
15
-
16
- if TYPE_CHECKING:
17
- from scapy.packet import Packet
18
-
19
- logger = logging.getLogger("nse.core.sniffer")
20
-
21
-
22
- class PCAPAsserter:
23
- """
24
- Asynchronous packet sniffer wrapper based on Scapy's AsyncSniffer.
25
- Used for asserting that no traffic leaks outside sandbox boundaries.
26
- """
27
-
28
- def __init__(self, iface: str, filter: str | None = None) -> None:
29
- from scapy.all import AsyncSniffer
30
-
31
- self.iface = iface
32
- # Ignore noisy background packets by default:
33
- # - arp: Address Resolution Protocol
34
- # - icmp6: IPv6 ICMP Router Solicitation/Advertisement and Neighbor discovery noise
35
- default_filter = "not arp and not icmp6"
36
- if filter:
37
- self.filter = f"({default_filter}) and ({filter})"
38
- else:
39
- self.filter = default_filter
40
-
41
- self._sniffer = AsyncSniffer(iface=self.iface, filter=self.filter)
42
-
43
- async def start(self) -> None:
44
- """Start the async sniffer."""
45
- logger.info(
46
- "Starting PCAP sniffer on %s with BPF filter: %s",
47
- self.iface,
48
- self.filter,
49
- )
50
- self._sniffer.start()
51
-
52
- async def stop(self) -> list[Packet]:
53
- """Stop the async sniffer and return captured packets."""
54
- logger.info("Stopping PCAP sniffer on %s", self.iface)
55
- loop = asyncio.get_running_loop()
56
- packets = await loop.run_in_executor(None, self._sniffer.stop)
57
- return list(packets) if packets is not None else []