okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221terminal: strata_cli, strata_control, bin/strata and the terminal tests64a91dcdc

main
8.8 KiB193 linesraw
1"""Offline policy tests (checklist U08).
2
3The checklist asks for two claims that are easy to conflate, and the whole point of these tests is
4that they are separate:
5
6* **runtime-only no-download** — the server fetches nothing while serving;
7* **strict offline** — nothing in the process tree reaches the network, including children, tools and
8  the agent runtime.
9
10A passing runtime-only test says nothing about the second: the first is about the server's own code
11paths, and the second is about every process it can start. So they are tested separately, and the
12strict tests check the actual environment a child receives rather than the flag that was passed.
13
14The limits are tested too. A policy that claims more than it enforces is worse than one that states
15its boundary, so `limits()` is asserted to be non-empty and specific.
16"""
17
18from __future__ import annotations
19
20import os
21import sys
22import unittest
23from pathlib import Path
24
25sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
26
27from strata_control import offline as O  # noqa: E402
28
29
30class TestUrlDecisions(unittest.TestCase):
31    """One predicate decides every fetch, so "offline" is not a scattered set of ifs."""
32
33    def test_a_remote_url_is_refused_when_offline(self):
34        decision = O.check_url("https://huggingface.co/model.bin", offline=True)
35        self.assertFalse(decision)
36        self.assertIn("huggingface.co", decision.reason)
37
38    def test_a_remote_url_is_allowed_when_not_offline(self):
39        self.assertTrue(O.check_url("https://huggingface.co/model.bin", offline=False))
40
41    def test_a_local_scheme_is_allowed_even_when_offline(self):
42        """Talking to this machine is not a download, and forbidding it would break the local API."""
43        for url in ("file:///tmp/image.png", "data:image/png;base64,AAAA"):
44            decision = O.check_url(url, offline=True)
45            self.assertTrue(decision, f"{url} must be allowed offline")
46
47    def test_loopback_over_http_is_allowed_when_offline(self):
48        for url in ("http://127.0.0.1:8095/v1/models", "http://localhost:8095/health",
49                    "http://[::1]:8095/health"):
50            self.assertTrue(O.check_url(url, offline=True), f"{url} is this machine")
51
52    def test_a_bare_path_is_allowed_when_offline(self):
53        """A profile usually names a local image as a path, not as a URL."""
54        self.assertTrue(O.check_url("/models/photo.png", offline=True))
55        self.assertTrue(O.check_url("photo.png", offline=True))
56
57    def test_a_non_http_scheme_is_refused_when_offline(self):
58        decision = O.check_url("ftp://example.com/x", offline=True)
59        self.assertFalse(decision)
60        self.assertIn("scheme", decision.reason)
61
62    def test_require_url_raises_with_the_reason(self):
63        with self.assertRaises(O.OfflineViolation) as ctx:
64            O.require_url("https://example.com/x", offline=True)
65        self.assertIn("would leave this machine", str(ctx.exception))
66        self.assertEqual(ctx.exception.url, "https://example.com/x")
67
68    def test_require_url_passes_a_local_url(self):
69        O.require_url("http://127.0.0.1:1/x", offline=True)      # must not raise
70
71
72class TestChildEnvironment(unittest.TestCase):
73    """Strict offline must reach code we do not own, which means the environment."""
74
75    def test_the_offline_markers_are_set_for_children(self):
76        env = O.child_environment(offline=True, base={})
77        self.assertEqual(env["HF_HUB_OFFLINE"], "1")
78        self.assertEqual(env["TRANSFORMERS_OFFLINE"], "1")
79        self.assertEqual(env["PIP_NO_INDEX"], "1")
80        self.assertEqual(env["STRATA_OFFLINE"], "1")
81
82    def test_proxies_are_emptied_so_an_accidental_call_fails_fast(self):
83        env = O.child_environment(offline=True,
84                                  base={"HTTPS_PROXY": "http://corp-proxy:8080"})
85        self.assertEqual(env["HTTPS_PROXY"], "")
86        self.assertEqual(env["NO_PROXY"], "*")
87
88    def test_the_parent_environment_is_not_mutated(self):
89        base = {"HTTPS_PROXY": "http://corp-proxy:8080", "PATH": "/usr/bin"}
90        O.child_environment(offline=True, base=base)
91        self.assertEqual(base["HTTPS_PROXY"], "http://corp-proxy:8080",
92                         "the caller's environment must be untouched")
93
94    def test_a_marker_from_a_previous_run_is_removed_when_not_offline(self):
95        """Otherwise a later server mysteriously refuses to fetch anything."""
96        env = O.child_environment(offline=False, base={"HF_HUB_OFFLINE": "1", "PATH": "/usr/bin"})
97        self.assertNotIn("HF_HUB_OFFLINE", env)
98        self.assertEqual(env["PATH"], "/usr/bin")
99
100    def test_the_real_environment_is_used_by_default(self):
101        env = O.child_environment(offline=True)
102        self.assertEqual(env["STRATA_OFFLINE"], "1")
103        self.assertIn("PATH", env, "the child still needs a PATH")
104
105
106class TestProfilePreflight(unittest.TestCase):
107    """Refusing before the server starts beats failing on the first request."""
108
109    def test_a_plain_profile_is_strictly_offline_capable(self):
110        self.assertEqual(O.ensure_strictly_offline({"model": "x", "args": []}), [])
111
112    def test_mcp_servers_are_named_as_a_reason(self):
113        reasons = O.ensure_strictly_offline({"mcp_servers": {"a": {}, "b": {}}})
114        self.assertTrue(reasons)
115        self.assertIn("2 MCP server", reasons[0])
116
117    def test_a_before_load_command_is_named_as_a_reason(self):
118        reasons = O.ensure_strictly_offline({"before_load": "curl https://example.com/x"})
119        self.assertTrue(reasons)
120        self.assertIn("before_load", reasons[0])
121
122    def test_remote_image_sources_are_named_as_a_reason(self):
123        reasons = O.ensure_strictly_offline({"images": {"allowed_hosts": ["cdn.example.com"]}})
124        self.assertTrue(reasons)
125        self.assertIn("images.allowed_hosts", reasons[0])
126
127    def test_a_local_image_section_is_not_a_reason(self):
128        self.assertEqual(O.ensure_strictly_offline({"images": {"size": 512}}), [])
129
130
131class TestTheLimitIsStated(unittest.TestCase):
132    """A policy that claims more than it enforces is worse than one that names its boundary."""
133
134    def test_the_limits_are_specific_and_non_empty(self):
135        limits = O.limits()
136        self.assertTrue(limits)
137        joined = " ".join(limits).lower()
138        self.assertIn("socket", joined, "the socket case is the one that matters")
139        self.assertIn("sandbox", joined)
140
141    def test_the_report_separates_the_two_claims(self):
142        report = O.report(offline=True, cfg={"model": "x"})
143        self.assertTrue(report["strict_offline"])
144        self.assertTrue(report["runtime_only_no_download"],
145                        "runtime-only is true independently of strict offline")
146        self.assertTrue(report["enforced"])
147        self.assertTrue(report["not_enforced"], "the limits travel with the claim")
148
149    def test_the_report_of_a_non_offline_run_does_not_claim_enforcement(self):
150        report = O.report(offline=False, cfg={})
151        self.assertFalse(report["strict_offline"])
152        self.assertEqual(report["not_enforced"], [])
153        self.assertTrue(report["runtime_only_no_download"])
154
155    def test_the_report_says_which_profile_parts_block_strict_offline(self):
156        report = O.report(offline=True, cfg={"mcp_servers": {"a": {}}})
157        self.assertTrue(report["profile_needs_network"])
158
159
160class TestTheServerUsesThePolicy(unittest.TestCase):
161    """A guard that is not wired in is decoration, so the wiring itself is asserted."""
162
163    def setUp(self):
164        self.source = (Path(__file__).resolve().parents[2] / "serve" / "server.py").read_text(
165            encoding="utf-8")
166
167    def test_the_image_path_consults_the_policy_or_the_flag(self):
168        # The reviewed server already refuses a remote image URL when offline; what matters here is
169        # that the refusal exists on both image paths rather than one.
170        self.assertGreaterEqual(self.source.count("offline mode cannot download an image URL"), 2,
171                                "both image paths must refuse a remote fetch")
172
173    def test_child_env_stamps_the_policy(self):
174        self.assertIn("offline_policy.OFFLINE_ENV", self.source,
175                      "children must be given the offline environment")
176
177    def test_every_child_environment_call_passes_the_policy(self):
178        """A single call site that forgot the flag would leak network access to that child."""
179        offenders = []
180        for index, line in enumerate(self.source.splitlines(), start=1):
181            if "child_env(" in line and "def child_env" not in line:
182                if "offline=" not in line:
183                    offenders.append(f"line {index}: {line.strip()}")
184        self.assertEqual(offenders, [],
185                         "every child_env call must pass the server's offline state: "
186                         + "; ".join(offenders))
187
188    def test_the_strict_offline_preflight_runs_before_serving(self):
189        self.assertIn("ensure_strictly_offline", self.source)
190
191
192if __name__ == "__main__":
193    unittest.main()