test_squid_config_splitter.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. """
  2. Tests for SquidConfigSplitter — the Squid config file splitting engine.
  3. """
  4. from unittest.mock import patch
  5. import pytest
  6. from services.squid import kerberos_config_service as kerberos
  7. from services.squid.squid_config_splitter import SquidConfigSplitter
  8. class TestClassifyLine:
  9. """Test the line classification engine."""
  10. @pytest.fixture(autouse=True)
  11. def _splitter(self):
  12. self.splitter = SquidConfigSplitter(input_file="/dev/null")
  13. @pytest.mark.parametrize(
  14. "line, expected_file",
  15. [
  16. ("http_port 3128", "00_ports.conf"),
  17. ("visible_hostname proxy", "10_misc.conf"),
  18. ("pid_filename /var/run/squid.pid", "10_misc.conf"),
  19. ("cache_mgr admin@example.com", "10_misc.conf"),
  20. ("forwarded_for off", "20_security.conf"),
  21. ("via off", "20_security.conf"),
  22. ("request_header_access Allow allow all", "20_security.conf"),
  23. ("cache_mem 64 MB", "30_cache.conf"),
  24. ("cache_dir ufs /spool 100 16 256", "30_cache.conf"),
  25. ("maximum_object_size 4 MB", "30_cache.conf"),
  26. ("refresh_pattern . 0 20% 4320", "40_refresh_patterns.conf"),
  27. ("auth_param basic program /usr/lib/squid/basic_ncsa_auth", "50_auth.conf"),
  28. ("acl auth proxy_auth REQUIRED", "50_auth.conf"),
  29. ("acl kerberos_auth proxy_auth REQUIRED", "50_auth.conf"),
  30. ("ssl_bump bump all", "55_ssl_bump.conf"),
  31. (
  32. "sslcrtd_program /usr/lib/squid/security_file_certgen",
  33. "55_ssl_bump.conf",
  34. ),
  35. ("acl step1 at_step SslBump1", "55_ssl_bump.conf"),
  36. ("access_log /var/log/squid/access.log", "60_logs.conf"),
  37. ("cache_log /var/log/squid/cache.log", "60_logs.conf"),
  38. ("logformat squid %ts.%03tu", "60_logs.conf"),
  39. ("coredump_dir /var/spool/squid", "60_logs.conf"),
  40. ("icap_enable on", "70_icap.conf"),
  41. ("adaptation_access service_resp allow all", "70_icap.conf"),
  42. ("dns_nameservers 8.8.8.8", "80_dns.conf"),
  43. ("hosts_file /etc/hosts", "80_dns.conf"),
  44. ("connect_timeout 30 seconds", "80_dns.conf"),
  45. ("include /etc/squid/block.txt", "90_includes.conf"),
  46. ("acl localhost src 127.0.0.1/32", "100_acls.conf"),
  47. ("acl red_local src 10.0.0.0/8", "100_acls.conf"),
  48. ("external_acl_type helper_name", "100_acls.conf"),
  49. ("delay_pools 3", "110_delay_pools.conf"),
  50. ("delay_class 1 2", "110_delay_pools.conf"),
  51. ("no_cache deny QUERY", "115_cache_control.conf"),
  52. (
  53. "cache_peer proxy1.alinet.cu parent 3128 0 round-robin proxy-only",
  54. "115_cache_control.conf",
  55. ),
  56. ("cache_peer_access proxy1 allow all", "115_cache_control.conf"),
  57. ("never_direct allow all", "115_cache_control.conf"),
  58. ("http_access allow localhost", "120_http_access.conf"),
  59. ("http_access deny all", "120_http_access.conf"),
  60. ("deny_info ERR_CUSTOM all", "120_http_access.conf"),
  61. ],
  62. )
  63. def test_classify_known_directives(self, line, expected_file):
  64. assert self.splitter._classify_line(line) == expected_file
  65. def test_classify_unknown_goes_to_999(self):
  66. assert (
  67. self.splitter._classify_line("some_random_directive value")
  68. == "999_unknown.conf"
  69. )
  70. class TestLoadOrder:
  71. """Test that the include load order is correct for dependency resolution."""
  72. def test_includes_before_acls(self):
  73. splitter = SquidConfigSplitter(input_file="/dev/null")
  74. order = splitter._get_load_order()
  75. idx_includes = order.index("90_includes.conf")
  76. idx_acls = order.index("100_acls.conf")
  77. idx_http = order.index("120_http_access.conf")
  78. assert idx_includes < idx_acls, "includes must load before ACLs"
  79. assert idx_acls < idx_http, "ACLs must load before http_access"
  80. def test_auth_before_acls(self):
  81. splitter = SquidConfigSplitter(input_file="/dev/null")
  82. order = splitter._get_load_order()
  83. idx_auth = order.index("50_auth.conf")
  84. idx_acls = order.index("100_acls.conf")
  85. assert idx_auth < idx_acls
  86. def test_delay_pools_after_acls(self):
  87. splitter = SquidConfigSplitter(input_file="/dev/null")
  88. order = splitter._get_load_order()
  89. idx_acls = order.index("100_acls.conf")
  90. idx_delay = order.index("110_delay_pools.conf")
  91. assert idx_acls < idx_delay
  92. class TestSplitConfig:
  93. """Test the full split_config workflow on temp files."""
  94. def test_split_creates_modular_files(self, tmp_squid_conf, tmp_path):
  95. output_dir = tmp_path / "squid.d"
  96. with patch.object(
  97. SquidConfigSplitter,
  98. "_validate_squid_config",
  99. return_value={"success": True, "output": ""},
  100. ):
  101. splitter = SquidConfigSplitter(
  102. input_file=str(tmp_squid_conf),
  103. output_dir=str(output_dir),
  104. )
  105. splitter.split_config()
  106. assert output_dir.exists()
  107. # Check expected files were created
  108. expected_files = [
  109. "00_ports.conf",
  110. "10_misc.conf",
  111. "20_security.conf",
  112. "30_cache.conf",
  113. "40_refresh_patterns.conf",
  114. "60_logs.conf",
  115. "100_acls.conf",
  116. "120_http_access.conf",
  117. ]
  118. created_files = [f.name for f in output_dir.iterdir() if f.suffix == ".conf"]
  119. for expected in expected_files:
  120. assert expected in created_files, f"{expected} should be created"
  121. def test_split_generates_main_config_with_includes(self, tmp_squid_conf, tmp_path):
  122. output_dir = tmp_path / "squid.d"
  123. with patch.object(
  124. SquidConfigSplitter,
  125. "_validate_squid_config",
  126. return_value={"success": True, "output": ""},
  127. ):
  128. splitter = SquidConfigSplitter(
  129. input_file=str(tmp_squid_conf),
  130. output_dir=str(output_dir),
  131. )
  132. splitter.split_config()
  133. main_content = tmp_squid_conf.read_text()
  134. assert "include" in main_content
  135. assert "SquidStats" in main_content # Header comment
  136. def test_split_with_include_directive(self, tmp_path):
  137. """Ensure include directives go to 90_includes.conf."""
  138. conf = tmp_path / "squid.conf"
  139. conf.write_text(
  140. "http_port 3128\n"
  141. "include /etc/squid/usuarios_bloqueados.txt\n"
  142. "acl localhost src 127.0.0.1\n"
  143. "http_access deny all\n",
  144. encoding="utf-8",
  145. )
  146. output_dir = tmp_path / "squid.d"
  147. with patch.object(
  148. SquidConfigSplitter,
  149. "_validate_squid_config",
  150. return_value={"success": True, "output": ""},
  151. ):
  152. splitter = SquidConfigSplitter(
  153. input_file=str(conf),
  154. output_dir=str(output_dir),
  155. )
  156. splitter.split_config()
  157. includes_file = output_dir / "90_includes.conf"
  158. assert includes_file.exists()
  159. content = includes_file.read_text()
  160. assert "include /etc/squid/usuarios_bloqueados.txt" in content
  161. def test_split_nonexistent_file_raises(self, tmp_path):
  162. splitter = SquidConfigSplitter(
  163. input_file=str(tmp_path / "nonexistent.conf"),
  164. output_dir=str(tmp_path / "out"),
  165. )
  166. with pytest.raises(FileNotFoundError):
  167. splitter.split_config()
  168. def test_split_handles_continuation_lines(self, tmp_path):
  169. """Backslash continuation lines should stay together."""
  170. conf = tmp_path / "squid.conf"
  171. conf.write_text(
  172. "http_port 3128 ssl-bump \\\n"
  173. " cert=/etc/ssl/squid.pem \\\n"
  174. " generate-host-certificates=on\n"
  175. "http_access deny all\n",
  176. encoding="utf-8",
  177. )
  178. output_dir = tmp_path / "squid.d"
  179. with patch.object(
  180. SquidConfigSplitter,
  181. "_validate_squid_config",
  182. return_value={"success": True, "output": ""},
  183. ):
  184. splitter = SquidConfigSplitter(
  185. input_file=str(conf),
  186. output_dir=str(output_dir),
  187. )
  188. splitter.split_config()
  189. ports_file = output_dir / "00_ports.conf"
  190. assert ports_file.exists()
  191. content = ports_file.read_text()
  192. assert "ssl-bump" in content
  193. assert "generate-host-certificates" in content
  194. def test_split_auth_detection(self, tmp_path):
  195. conf = tmp_path / "squid.conf"
  196. conf.write_text(
  197. "http_port 3128\n"
  198. "auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/passwd\n"
  199. "acl auth proxy_auth REQUIRED\n"
  200. "http_access allow auth\n"
  201. "http_access deny all\n",
  202. encoding="utf-8",
  203. )
  204. output_dir = tmp_path / "squid.d"
  205. with patch.object(
  206. SquidConfigSplitter,
  207. "_validate_squid_config",
  208. return_value={"success": True, "output": ""},
  209. ):
  210. splitter = SquidConfigSplitter(
  211. input_file=str(conf),
  212. output_dir=str(output_dir),
  213. )
  214. splitter.split_config()
  215. auth_file = output_dir / "50_auth.conf"
  216. assert auth_file.exists()
  217. assert splitter.has_auth is True
  218. def test_split_rejects_an_active_managed_kerberos_configuration(self, tmp_path):
  219. """The splitter cannot preserve arbitrary Kerberos policy ordering."""
  220. conf = tmp_path / "squid.conf"
  221. original = (
  222. "http_port 3128\n"
  223. "# BEGIN SquidStats Kerberos authentication\n"
  224. "auth_param negotiate program /opt/helper -k /etc/squid/HTTP.keytab "
  225. "-s HTTP/proxy.example@EXAMPLE\n"
  226. "acl kerberos_auth proxy_auth REQUIRED\n"
  227. "# END SquidStats Kerberos authentication\n"
  228. "# BEGIN SquidStats Kerberos access rule\n"
  229. "http_access deny !kerberos_auth\n"
  230. "# END SquidStats Kerberos access rule\n"
  231. "http_access allow localnet\n"
  232. "http_access deny all\n"
  233. )
  234. conf.write_text(original, encoding="utf-8")
  235. output_dir = tmp_path / "squid.d"
  236. splitter = SquidConfigSplitter(input_file=str(conf), output_dir=str(output_dir))
  237. with pytest.raises(RuntimeError, match="Kerberos/Negotiate"):
  238. splitter.split_config()
  239. assert conf.read_text(encoding="utf-8") == original
  240. assert not output_dir.exists()
  241. def test_split_rejects_negotiate_from_an_active_nested_include(self, tmp_path):
  242. """A modular Kerberos helper is protected even when main only includes a parent."""
  243. conf = tmp_path / "squid.conf"
  244. parent = tmp_path / "parent.conf"
  245. parent.write_text(
  246. "auth_param negotiate program /opt/helper -k /etc/squid/HTTP.keytab "
  247. "-s HTTP/proxy.example@EXAMPLE\n",
  248. encoding="utf-8",
  249. )
  250. conf.write_text("include parent.conf\n", encoding="utf-8")
  251. splitter = SquidConfigSplitter(
  252. input_file=str(conf), output_dir=str(tmp_path / "squid.d")
  253. )
  254. with pytest.raises(RuntimeError, match="Kerberos/Negotiate"):
  255. splitter.split_config()
  256. assert conf.read_text(encoding="utf-8") == "include parent.conf\n"
  257. def test_split_rejects_multiline_negotiate_directive(self, tmp_path):
  258. """A valid backslash continuation cannot evade the Kerberos guard."""
  259. conf = tmp_path / "squid.conf"
  260. original = (
  261. "http_port 3128\n"
  262. + "auth_param "
  263. + "\\"
  264. + "\n"
  265. + " negotiate program /opt/helper -k /etc/squid/HTTP.keytab "
  266. + "-s HTTP/proxy.example@EXAMPLE\n"
  267. + "acl kerberos_auth proxy_auth REQUIRED\n"
  268. + "http_access deny !kerberos_auth\n"
  269. + "http_access allow localnet\n"
  270. + "http_access deny all\n"
  271. )
  272. conf.write_text(original, encoding="utf-8")
  273. output_dir = tmp_path / "squid.d"
  274. splitter = SquidConfigSplitter(input_file=str(conf), output_dir=str(output_dir))
  275. with pytest.raises(RuntimeError, match="Kerberos/Negotiate"):
  276. splitter.split_config()
  277. assert conf.read_text(encoding="utf-8") == original
  278. assert not output_dir.exists()
  279. def test_split_validation_uses_the_selected_docker_runtime(
  280. self, tmp_path, monkeypatch
  281. ):
  282. """Docker validation must use its configured container config path."""
  283. config_path = tmp_path / "squid.conf"
  284. config_path.write_text("http_port 3128\n", encoding="utf-8")
  285. splitter = SquidConfigSplitter(input_file=str(config_path))
  286. runtime = kerberos._SquidRuntime(
  287. kind="docker",
  288. executable="/usr/bin/docker",
  289. container_name="configured-squid",
  290. container_config_path="/etc/squid/custom.conf",
  291. )
  292. captured: list[tuple[str, object]] = []
  293. monkeypatch.setattr(kerberos, "_find_squid_runtime", lambda: runtime)
  294. monkeypatch.setattr(kerberos, "_docker_mounts", lambda _runtime: [])
  295. monkeypatch.setattr(
  296. kerberos,
  297. "_docker_config_mount_status",
  298. lambda *args, **kwargs: {"mapped": True},
  299. )
  300. def validate(path, selected_runtime):
  301. captured.append((str(path), selected_runtime))
  302. return {"available": True, "valid": True, "message": "ok"}
  303. monkeypatch.setattr(kerberos, "validate_squid_configuration", validate)
  304. result = splitter._validate_squid_config()
  305. assert result["success"] is True
  306. assert captured == [(str(config_path), runtime)]
  307. def test_split_rejects_docker_with_an_invalid_container_config_path(
  308. self, tmp_path, monkeypatch
  309. ):
  310. """Do not validate the image default after editing another host config."""
  311. config_path = tmp_path / "squid.conf"
  312. config_path.write_text("http_port 3128\n", encoding="utf-8")
  313. splitter = SquidConfigSplitter(input_file=str(config_path))
  314. runtime = kerberos._SquidRuntime(
  315. kind="docker",
  316. executable="/usr/bin/docker",
  317. container_name="configured-squid",
  318. container_config_path=None,
  319. )
  320. monkeypatch.setattr(kerberos, "_find_squid_runtime", lambda: runtime)
  321. result = splitter._validate_squid_config()
  322. assert result["success"] is False
  323. assert "SQUID_CONTAINER_CONFIG_PATH" in result["error_message"]
  324. def test_failed_split_restores_every_generated_module(self, tmp_path):
  325. """Validation failure cannot leave active wildcard modules behind."""
  326. output_dir = tmp_path / "squid.d"
  327. output_dir.mkdir()
  328. old_ports = "# Existing module loaded by the original wildcard\n"
  329. (output_dir / "00_ports.conf").write_text(old_ports, encoding="utf-8")
  330. conf = tmp_path / "squid.conf"
  331. original = (
  332. "http_port 3128\n"
  333. "include squid.d/*.conf\n"
  334. "acl localnet src 10.0.0.0/8\n"
  335. "http_access allow localnet\n"
  336. "http_access deny all\n"
  337. )
  338. conf.write_text(original, encoding="utf-8")
  339. splitter = SquidConfigSplitter(input_file=str(conf), output_dir=str(output_dir))
  340. with patch.object(
  341. SquidConfigSplitter,
  342. "_validate_squid_config",
  343. return_value={"success": False, "error_message": "synthetic parse error"},
  344. ):
  345. with pytest.raises(RuntimeError, match="Changes have been reverted"):
  346. splitter.split_config()
  347. assert conf.read_text(encoding="utf-8") == original
  348. assert (output_dir / "00_ports.conf").read_text(encoding="utf-8") == old_ports
  349. assert not (output_dir / "100_acls.conf").exists()
  350. assert not (output_dir / "120_http_access.conf").exists()
  351. def test_split_does_not_overwrite_a_module_changed_after_snapshot(
  352. self, tmp_path, monkeypatch
  353. ):
  354. """A manual change between snapshot and write aborts without losing it."""
  355. output_dir = tmp_path / "squid.d"
  356. output_dir.mkdir()
  357. acl_path = output_dir / "100_acls.conf"
  358. acl_path.write_text("acl legacy src 10.0.0.0/8\n", encoding="utf-8")
  359. conf = tmp_path / "squid.conf"
  360. original = (
  361. "http_port 3128\n"
  362. "acl localnet src 192.168.0.0/16\n"
  363. "http_access allow localnet\n"
  364. "http_access deny all\n"
  365. )
  366. conf.write_text(original, encoding="utf-8")
  367. splitter = SquidConfigSplitter(input_file=str(conf), output_dir=str(output_dir))
  368. original_assert = splitter._assert_snapshot_is_current
  369. injected = False
  370. def assert_with_external_change(snapshot):
  371. nonlocal injected
  372. if snapshot.path == str(acl_path) and not injected:
  373. acl_path.write_text(
  374. "# changed outside the transaction\n", encoding="utf-8"
  375. )
  376. injected = True
  377. original_assert(snapshot)
  378. monkeypatch.setattr(
  379. splitter, "_assert_snapshot_is_current", assert_with_external_change
  380. )
  381. with patch.object(
  382. SquidConfigSplitter,
  383. "_validate_squid_config",
  384. return_value={"success": True, "output": ""},
  385. ):
  386. with pytest.raises(RuntimeError, match="cambió durante la operación"):
  387. splitter.split_config()
  388. assert injected is True
  389. assert conf.read_text(encoding="utf-8") == original
  390. assert (
  391. acl_path.read_text(encoding="utf-8")
  392. == "# changed outside the transaction\n"
  393. )
  394. def test_split_preserves_a_symbolic_main_config_link(self, tmp_path):
  395. """The splitter uses the same symlink-safe writer as other editors."""
  396. target = tmp_path / "actual-squid.conf"
  397. target.write_text("http_port 3128\nhttp_access deny all\n", encoding="utf-8")
  398. config_path = tmp_path / "squid.conf"
  399. config_path.symlink_to(target.name)
  400. with patch.object(
  401. SquidConfigSplitter,
  402. "_validate_squid_config",
  403. return_value={"success": True, "output": ""},
  404. ):
  405. SquidConfigSplitter(
  406. input_file=str(config_path), output_dir=str(tmp_path / "squid.d")
  407. ).split_config()
  408. assert config_path.is_symlink()
  409. assert "include" in target.read_text(encoding="utf-8")
  410. def test_backup_disabled(self, tmp_squid_conf, tmp_path):
  411. """Backup creation is currently disabled — no .bak files should appear."""
  412. output_dir = tmp_path / "squid.d"
  413. with patch.object(
  414. SquidConfigSplitter,
  415. "_validate_squid_config",
  416. return_value={"success": True, "output": ""},
  417. ):
  418. splitter = SquidConfigSplitter(
  419. input_file=str(tmp_squid_conf),
  420. output_dir=str(output_dir),
  421. )
  422. splitter.split_config()
  423. bak_files = list(tmp_path.glob("*.bak*"))
  424. assert len(bak_files) == 0, "No .bak files should be created"
  425. class TestGetSplitInfo:
  426. def test_returns_dict_of_descriptions(self):
  427. splitter = SquidConfigSplitter(input_file="/dev/null")
  428. info = splitter.get_split_info()
  429. assert isinstance(info, dict)
  430. assert "00_ports.conf" in info
  431. assert "120_http_access.conf" in info
  432. assert "999_unknown.conf" in info