test_kerberos_integration_safety.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. """Regression tests for Kerberos interactions with generic config features."""
  2. from __future__ import annotations
  3. import os
  4. import stat
  5. from pathlib import Path
  6. from types import SimpleNamespace
  7. import pytest
  8. from services.quota.quota_service import _ensure_quota_http_rule
  9. from services.squid.acls_service import add_acl, delete_acl, edit_acl
  10. from services.squid.http_access_service import edit_http_access
  11. from utils.admin import SquidConfigManager, _replacement_ownership
  12. class _AclManager:
  13. """Minimal monolithic manager for the generic ACL editor tests."""
  14. is_modular = False
  15. def __init__(self, content: str, acls: list[dict]) -> None:
  16. self.config_content = content
  17. self._acls = acls
  18. self.saved: list[str] = []
  19. def get_acls(self):
  20. return self._acls
  21. def save_config(self, content: str) -> bool:
  22. self.saved.append(content)
  23. self.config_content = content
  24. return True
  25. class _AuthStatusManager:
  26. """Use the production active-include scanner with fixture files."""
  27. _active_configuration_contents = SquidConfigManager._active_configuration_contents
  28. has_proxy_authentication = SquidConfigManager.has_proxy_authentication
  29. def __init__(self, config_path, content: str) -> None:
  30. self.config_path = str(config_path)
  31. self.config_content = content
  32. self.is_valid = True
  33. class _RefreshingAclManager(_AclManager):
  34. """A long-lived editor manager whose on-disk config changed meanwhile."""
  35. def __init__(self, config_path, initial_content: str, current_content: str) -> None:
  36. super().__init__(initial_content, [{"name": "manager", "line_number": 1}])
  37. self.config_path = str(config_path)
  38. config_path.write_text(current_content, encoding="utf-8")
  39. def load_config(self) -> bool:
  40. self.config_content = Path(self.config_path).read_text(encoding="utf-8")
  41. return True
  42. def _check_modular_config(self) -> None:
  43. return None
  44. def test_generic_acl_editor_cannot_mutate_managed_kerberos_identity_acl():
  45. content = (
  46. "# BEGIN SquidStats Kerberos authentication\n"
  47. "auth_param negotiate program /opt/helper -k /etc/squid/HTTP.keytab "
  48. "-s HTTP/proxy.example@EXAMPLE\n"
  49. "acl kerberos_auth proxy_auth REQUIRED\n"
  50. "# END SquidStats Kerberos authentication\n"
  51. )
  52. manager = _AclManager(
  53. content,
  54. [{"name": "kerberos_auth", "line_number": 3}],
  55. )
  56. assert add_acl("kerberos_auth", "src", ["10.0.0.0/8"], [], "", manager)[0] is False
  57. assert edit_acl(0, "other_name", "src", ["10.0.0.0/8"], [], "", manager)[0] is False
  58. assert delete_acl(0, manager)[0] is False
  59. assert manager.saved == []
  60. def test_generic_acl_editor_cannot_rename_an_acl_to_the_managed_name():
  61. content = (
  62. "# BEGIN SquidStats Kerberos authentication\n"
  63. "acl kerberos_auth proxy_auth REQUIRED\n"
  64. "# END SquidStats Kerberos authentication\n"
  65. "acl office src 10.0.0.0/8\n"
  66. )
  67. manager = _AclManager(content, [{"name": "office", "line_number": 4}])
  68. ok, _message = edit_acl(
  69. 0,
  70. "kerberos_auth",
  71. "src",
  72. ["10.0.0.0/8"],
  73. [],
  74. "",
  75. manager,
  76. )
  77. assert ok is False
  78. assert manager.saved == []
  79. def test_generic_acl_editor_cannot_broaden_the_pre_kerberos_manager_exception():
  80. """The manager/localhost ACLs are part of the managed access invariant."""
  81. content = "\n".join(
  82. [
  83. "acl manager proto cache_object",
  84. "acl localhost src 127.0.0.1/32 ::1",
  85. "# BEGIN SquidStats Kerberos access rule",
  86. "http_access deny !kerberos_auth",
  87. "# END SquidStats Kerberos access rule",
  88. ]
  89. )
  90. manager = _AclManager(
  91. content,
  92. [
  93. {"name": "manager", "line_number": 1},
  94. {"name": "localhost", "line_number": 2},
  95. ],
  96. )
  97. assert add_acl("manager", "all", [""], [], "", manager)[0] is False
  98. assert edit_acl(0, "manager", "all", [""], [], "", manager)[0] is False
  99. assert delete_acl(1, manager)[0] is False
  100. assert manager.saved == []
  101. def test_acl_editor_rechecks_kerberos_after_waiting_for_the_config_lock(tmp_path):
  102. """A stale request cannot broaden manager after a Kerberos apply wins."""
  103. initial = "acl manager proto cache_object\n"
  104. current = "\n".join(
  105. [
  106. initial.rstrip(),
  107. "# BEGIN SquidStats Kerberos access rule",
  108. "http_access deny !kerberos_auth",
  109. "# END SquidStats Kerberos access rule",
  110. ]
  111. )
  112. manager = _RefreshingAclManager(tmp_path / "squid.conf", initial, current)
  113. ok, _message = edit_acl(0, "manager", "all", [""], [], "", manager)
  114. assert ok is False
  115. assert manager.saved == []
  116. def test_proxy_auth_quota_rule_stays_after_manager_and_kerberos_blocks():
  117. lines = [
  118. "http_access allow manager localhost",
  119. "http_access deny manager",
  120. "http_access deny !Safe_ports",
  121. "# BEGIN SquidStats Kerberos access rule",
  122. "http_access deny !kerberos_auth",
  123. "# END SquidStats Kerberos access rule",
  124. "http_access allow localnet",
  125. "http_access deny all",
  126. ]
  127. updated = _ensure_quota_http_rule(
  128. lines, "http_access deny usuarios_bloqueados", use_src=False
  129. )
  130. assert updated.index("http_access allow manager localhost") < updated.index(
  131. "http_access deny usuarios_bloqueados"
  132. )
  133. assert (
  134. updated.index("# END SquidStats Kerberos access rule")
  135. < updated.index("http_access deny usuarios_bloqueados")
  136. < updated.index("http_access allow localnet")
  137. )
  138. def test_proxy_auth_quota_rule_respects_reversed_manager_exception():
  139. """The Cache Manager ACL order is conjunctive, so either order is safe."""
  140. lines = [
  141. "http_access allow localhost manager",
  142. "http_access deny manager",
  143. "http_access deny !Safe_ports",
  144. "http_access allow localnet",
  145. "http_access deny all",
  146. ]
  147. updated = _ensure_quota_http_rule(
  148. lines, "http_access deny usuarios_bloqueados", use_src=False
  149. )
  150. assert (
  151. updated.index("http_access allow localhost manager")
  152. < updated.index("http_access deny usuarios_bloqueados")
  153. < updated.index("http_access allow localnet")
  154. )
  155. def test_existing_proxy_auth_quota_rule_is_repositioned_safely():
  156. lines = [
  157. "http_access deny usuarios_bloqueados",
  158. "http_access allow manager localhost",
  159. "http_access deny manager",
  160. "# BEGIN SquidStats Kerberos access rule",
  161. "http_access deny !kerberos_auth",
  162. "# END SquidStats Kerberos access rule",
  163. "http_access allow localnet",
  164. "http_access deny all",
  165. ]
  166. updated = _ensure_quota_http_rule(
  167. lines, "http_access deny usuarios_bloqueados", use_src=False
  168. )
  169. assert updated.count("http_access deny usuarios_bloqueados") == 1
  170. assert updated.index("http_access deny usuarios_bloqueados") > updated.index(
  171. "# END SquidStats Kerberos access rule"
  172. )
  173. def test_http_editor_cannot_turn_a_pre_kerberos_rule_into_a_client_allow():
  174. """Editing a neighboring rule must not bypass the managed challenge."""
  175. manager = _AclManager(
  176. "\n".join(
  177. [
  178. "http_access allow manager localhost",
  179. "http_access deny manager",
  180. "# BEGIN SquidStats Kerberos access rule",
  181. "http_access deny !kerberos_auth",
  182. "# END SquidStats Kerberos access rule",
  183. "http_access allow localnet",
  184. "http_access deny all",
  185. ]
  186. ),
  187. [],
  188. )
  189. ok, message = edit_http_access(0, "allow", ["localnet"], "", manager)
  190. assert ok is False
  191. assert "antes del desafío Kerberos" in message
  192. assert manager.saved == []
  193. def test_http_editor_keeps_an_undocumented_rule_without_an_empty_comment():
  194. """The generic editor must still save ordinary HTTP rules unchanged."""
  195. manager = _AclManager("http_access allow localnet", [])
  196. ok, _message = edit_http_access(0, "allow", ["office"], "", manager)
  197. assert ok is True
  198. assert manager.config_content == "http_access allow office"
  199. assert "# " not in manager.config_content
  200. def test_http_editor_accepts_the_conventional_reversed_manager_exception():
  201. """``allow localhost manager`` is just as narrow as the other order."""
  202. manager = _AclManager(
  203. "\n".join(
  204. [
  205. "http_access allow localhost manager",
  206. "http_access deny manager",
  207. "# BEGIN SquidStats Kerberos access rule",
  208. "http_access deny !kerberos_auth",
  209. "# END SquidStats Kerberos access rule",
  210. "http_access allow localnet",
  211. "http_access deny all",
  212. ]
  213. ),
  214. [],
  215. )
  216. ok, _message = edit_http_access(3, "allow", ["office"], "", manager)
  217. assert ok is True
  218. assert "http_access allow office" in manager.config_content
  219. def test_proxy_auth_status_ignores_a_stale_unincluded_auth_module(tmp_path):
  220. module_dir = tmp_path / "squid.d"
  221. module_dir.mkdir()
  222. (module_dir / "50_auth.conf").write_text(
  223. "auth_param negotiate program /opt/helper\n"
  224. "acl kerberos_auth proxy_auth REQUIRED\n",
  225. encoding="utf-8",
  226. )
  227. config_path = tmp_path / "squid.conf"
  228. config_path.write_text(
  229. f"include {module_dir / '120_http_access.conf'}\n", encoding="utf-8"
  230. )
  231. manager = _AuthStatusManager(config_path, config_path.read_text(encoding="utf-8"))
  232. assert manager.has_proxy_authentication() is False
  233. config_path.write_text(f"include {module_dir / '*.conf'}\n", encoding="utf-8")
  234. manager.config_content = config_path.read_text(encoding="utf-8")
  235. assert manager.has_proxy_authentication() is True
  236. def test_modular_detection_supports_a_continued_include_directive(tmp_path):
  237. """Kerberos must select modules when Squid wraps an include line."""
  238. module_dir = tmp_path / "squid.d"
  239. module_dir.mkdir()
  240. manager = SquidConfigManager.__new__(SquidConfigManager)
  241. manager.config_path = str(tmp_path / "squid.conf")
  242. manager.config_dir = str(module_dir)
  243. manager.config_content = "http_port 3128\ninclude \\\n squid.d/*.conf\n"
  244. manager.is_modular = False
  245. manager._check_modular_config()
  246. assert manager.is_modular is True
  247. assert manager.config_dir == str(module_dir)
  248. def test_atomic_writes_preserve_existing_squid_config_permissions(tmp_path):
  249. config_path = tmp_path / "squid.conf"
  250. config_path.write_text("before\n", encoding="utf-8")
  251. os.chmod(config_path, 0o640)
  252. SquidConfigManager._atomic_write(str(config_path), "after\n")
  253. result = config_path.stat()
  254. assert config_path.read_text(encoding="utf-8") == "after\n"
  255. assert stat.S_IMODE(result.st_mode) == 0o640
  256. def test_unprivileged_atomic_replacement_preserves_an_allowed_squid_group(
  257. monkeypatch,
  258. ):
  259. """Directory ACLs must not force an impossible root-owner fchown."""
  260. metadata = SimpleNamespace(st_uid=0, st_gid=4567, st_mode=0o640)
  261. monkeypatch.setattr("utils.admin.os.geteuid", lambda: 1234)
  262. monkeypatch.setattr("utils.admin.os.getegid", lambda: 1234)
  263. monkeypatch.setattr("utils.admin.os.getgroups", lambda: [4567])
  264. assert _replacement_ownership(metadata) == (-1, 4567)
  265. def test_unprivileged_atomic_replacement_rejects_unreadable_foreign_group(
  266. monkeypatch,
  267. ):
  268. """Do not replace a protected file with one Squid may no longer read."""
  269. metadata = SimpleNamespace(st_uid=0, st_gid=4567, st_mode=0o640)
  270. monkeypatch.setattr("utils.admin.os.geteuid", lambda: 1234)
  271. monkeypatch.setattr("utils.admin.os.getegid", lambda: 1234)
  272. monkeypatch.setattr("utils.admin.os.getgroups", lambda: [])
  273. with pytest.raises(PermissionError, match="conservar el grupo"):
  274. _replacement_ownership(metadata)
  275. def test_atomic_writes_make_new_generated_config_modules_readable(tmp_path):
  276. module_path = tmp_path / "50_auth.conf"
  277. SquidConfigManager._atomic_write(str(module_path), "# generated\n")
  278. assert stat.S_IMODE(module_path.stat().st_mode) == 0o644
  279. def test_atomic_write_preserves_a_squid_config_symlink(tmp_path):
  280. target = tmp_path / "actual-squid.conf"
  281. target.write_text("before\n", encoding="utf-8")
  282. config_path = tmp_path / "squid.conf"
  283. config_path.symlink_to(target.name)
  284. SquidConfigManager._atomic_write(str(config_path), "after\n")
  285. assert config_path.is_symlink()
  286. assert target.read_text(encoding="utf-8") == "after\n"
  287. def test_stale_main_config_snapshot_is_not_overwritten(tmp_path):
  288. """A second writer must reload instead of erasing a Kerberos update."""
  289. config_path = tmp_path / "squid.conf"
  290. config_path.write_text("newer Kerberos config\n", encoding="utf-8")
  291. manager = SquidConfigManager.__new__(SquidConfigManager)
  292. manager.config_path = str(config_path)
  293. manager.config_content = "older config\n"
  294. manager._modular_content_snapshots = {}
  295. manager.is_valid = True
  296. assert manager.save_config("unrelated change\n") is False
  297. assert config_path.read_text(encoding="utf-8") == "newer Kerberos config\n"
  298. def test_stale_modular_snapshot_is_not_overwritten(tmp_path):
  299. """The shared save path also protects 120_http_access.conf."""
  300. module_path = tmp_path / "120_http_access.conf"
  301. module_path.write_text("newer Kerberos challenge\n", encoding="utf-8")
  302. manager = SquidConfigManager.__new__(SquidConfigManager)
  303. manager.config_path = str(tmp_path / "squid.conf")
  304. manager.config_dir = str(tmp_path)
  305. manager._modular_content_snapshots = {
  306. "120_http_access.conf": "older access policy\n"
  307. }
  308. manager.is_valid = True
  309. assert (
  310. manager.save_modular_config("120_http_access.conf", "quota snapshot\n") is False
  311. )
  312. assert module_path.read_text(encoding="utf-8") == "newer Kerberos challenge\n"