quota_service.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. import ipaddress
  2. import os
  3. import re
  4. import subprocess # nosec B404
  5. from collections.abc import Callable
  6. from loguru import logger
  7. from services.squid.kerberos_config_service import (
  8. _active_included_configuration_sources,
  9. _find_squid_runtime,
  10. reconfigure_squid,
  11. )
  12. from services.squid.squid_config_splitter import SquidConfigSplitter
  13. from utils.admin import SquidConfigManager, squid_config_write_lock
  14. _BLOCKED_USERS_PATH = "/etc/squid/usuarios_bloqueados.txt"
  15. _KERBEROS_AUTH_START = "# BEGIN SquidStats Kerberos authentication"
  16. _KERBEROS_AUTH_END = "# END SquidStats Kerberos authentication"
  17. _KERBEROS_ACCESS_START = "# BEGIN SquidStats Kerberos access rule"
  18. _KERBEROS_ACCESS_END = "# END SquidStats Kerberos access rule"
  19. def _normalised_squid_line(line: str) -> str:
  20. """Return a directive suitable for exact ownership checks.
  21. The quota feature owns only its generated ACL/include pair. Comparing
  22. tokens rather than prefixes prevents a similarly named administrator ACL
  23. (for example ``usuarios_bloqueados_extra``) from being removed.
  24. """
  25. return line.strip().split("#", 1)[0].strip()
  26. def _is_quota_acl_entry(line: str, blocked_path: str) -> bool:
  27. """Whether *line* is either generated representation of the quota ACL.
  28. Before proxy authentication is configured, the quota list is a Squid
  29. ``include`` containing ``acl ... src`` entries. With authentication it
  30. becomes a ``proxy_auth -i`` value list. They are mutually exclusive:
  31. retaining both during a transition can either duplicate the ACL name or
  32. make Squid parse plain usernames as configuration directives.
  33. """
  34. parts = _normalised_squid_line(line).split()
  35. if not parts:
  36. return False
  37. if (
  38. len(parts) == 2
  39. and parts[0].casefold() == "include"
  40. and parts[1].strip('"').strip("'") == blocked_path
  41. ):
  42. return True
  43. return (
  44. len(parts) >= 2
  45. and parts[0].casefold() == "acl"
  46. and parts[1].casefold() == "usuarios_bloqueados"
  47. )
  48. def _normalised_http_access_line(line: str) -> str:
  49. """Return a comparable Squid directive without an inline comment."""
  50. return line.strip().split("#", 1)[0].strip()
  51. def _is_local_cache_manager_allow(line: str) -> bool:
  52. """Whether a line is the narrow Cache Manager exception.
  53. A broad ``allow manager`` or a negated ACL must not be treated as the
  54. management exception because either may authorize ordinary proxy traffic.
  55. """
  56. parts = _normalised_http_access_line(line).split()
  57. lowered = [part.casefold() for part in parts]
  58. return (
  59. len(lowered) == 4
  60. and lowered[:2] == ["http_access", "allow"]
  61. and set(lowered[2:]) == {"manager", "localhost"}
  62. )
  63. def _managed_kerberos_modular_layout_is_supported(cm: SquidConfigManager) -> bool:
  64. """Refuse quota writes to inactive/ambiguous modules under Kerberos.
  65. Kerberos can safely manage a monolithic policy, or its dedicated standard
  66. modules. A generic modular flag alone is not enough: it may be caused by
  67. a custom include while the active HTTP policy still lives in squid.conf.
  68. In that situation writing quota ACL/rules to 100/120 would either do
  69. nothing or create an allow/deny ordering the daemon never validated.
  70. """
  71. if not cm.is_modular:
  72. return True
  73. inspection_errors: list[str] = []
  74. try:
  75. included_sources = _active_included_configuration_sources(
  76. cm, inspection_errors=inspection_errors
  77. )
  78. except Exception as exc:
  79. logger.error(
  80. "No se pudieron inspeccionar includes para cuotas Kerberos: {}", exc
  81. )
  82. return False
  83. main_path = os.path.realpath(cm.config_path)
  84. sources = [(main_path, cm.config_content or ""), *included_sources]
  85. managed_access_sources = [
  86. path
  87. for path, content in sources
  88. if _KERBEROS_ACCESS_START in content and _KERBEROS_ACCESS_END in content
  89. ]
  90. if not managed_access_sources:
  91. return True
  92. expected_paths = {
  93. "auth": os.path.realpath(os.path.join(cm.config_dir, "50_auth.conf")),
  94. "acls": os.path.realpath(os.path.join(cm.config_dir, "100_acls.conf")),
  95. "access": os.path.realpath(os.path.join(cm.config_dir, "120_http_access.conf")),
  96. }
  97. active_contents = {os.path.realpath(path): content for path, content in sources}
  98. auth_content = active_contents.get(expected_paths["auth"], "")
  99. if (
  100. inspection_errors
  101. or expected_paths["acls"] not in active_contents
  102. or _KERBEROS_AUTH_START not in auth_content
  103. or _KERBEROS_AUTH_END not in auth_content
  104. or expected_paths["access"] not in managed_access_sources
  105. ):
  106. logger.error(
  107. "No se sincronizaron cuotas: Kerberos está activo en un diseño modular "
  108. "que no usa 50_auth.conf, 100_acls.conf y 120_http_access.conf activos "
  109. "en sus ubicaciones estándar. Migra la política desde Kerberos / SPNEGO."
  110. )
  111. return False
  112. return True
  113. def _proxy_auth_deny_insert_index(lines: list[str]) -> int:
  114. """Choose a safe position for the quota's proxy-auth denial.
  115. A proxy-auth ACL can initiate an authentication lookup. It therefore has
  116. to remain after the local Cache Manager exception and after the managed
  117. Kerberos challenge, but before the first normal client allow rule.
  118. """
  119. managed_end = next(
  120. (
  121. index + 1
  122. for index, line in enumerate(lines)
  123. if line.strip() == _KERBEROS_ACCESS_END
  124. ),
  125. None,
  126. )
  127. if managed_end is not None:
  128. return managed_end
  129. first_client_allow = next(
  130. (
  131. index
  132. for index, line in enumerate(lines)
  133. if _normalised_http_access_line(line)
  134. .casefold()
  135. .startswith("http_access allow")
  136. and not _is_local_cache_manager_allow(line)
  137. ),
  138. None,
  139. )
  140. if first_client_allow is None:
  141. # Keep a deny rule reachable when a configuration lacks a normal allow
  142. # line, without placing it after the final catch-all deny.
  143. return next(
  144. (
  145. index
  146. for index, line in enumerate(lines)
  147. if _normalised_http_access_line(line).casefold()
  148. == "http_access deny all"
  149. ),
  150. len(lines),
  151. )
  152. # Security denials and a manual proxy-auth challenge belong before the
  153. # quota rule. Insert after the last such denial, yet before the client
  154. # allow that would otherwise bypass it.
  155. last_deny = max(
  156. (
  157. index
  158. for index, line in enumerate(lines[:first_client_allow])
  159. if _normalised_http_access_line(line)
  160. .casefold()
  161. .startswith("http_access deny")
  162. ),
  163. default=None,
  164. )
  165. return last_deny + 1 if last_deny is not None else first_client_allow
  166. def _ensure_quota_http_rule(
  167. lines: list[str], http_line: str, *, use_src: bool
  168. ) -> list[str]:
  169. """Add (or reposition) the quota deny rule without bypassing auth.
  170. The IP-based fallback keeps its historical early placement. A quota that
  171. uses ``proxy_auth`` is ordered deliberately because touching it before the
  172. Cache Manager exception can turn local manager requests into 407s.
  173. """
  174. def is_quota_rule(line: str) -> bool:
  175. return _normalised_http_access_line(line).casefold() == http_line.casefold()
  176. if use_src:
  177. if any(is_quota_rule(line) for line in lines):
  178. return lines
  179. insertion = next(
  180. (
  181. index
  182. for index, line in enumerate(lines)
  183. if _normalised_http_access_line(line)
  184. .casefold()
  185. .startswith("http_access ")
  186. ),
  187. len(lines),
  188. )
  189. return [*lines[:insertion], http_line, *lines[insertion:]]
  190. without_existing = [line for line in lines if not is_quota_rule(line)]
  191. insertion = _proxy_auth_deny_insert_index(without_existing)
  192. return [
  193. *without_existing[:insertion],
  194. http_line,
  195. *without_existing[insertion:],
  196. ]
  197. def _file_has_content(path: str) -> bool:
  198. """Devuelve True si el archivo existe y contiene al menos una entrada real."""
  199. try:
  200. if not os.path.exists(path):
  201. return False
  202. with open(path, encoding="utf-8") as f:
  203. for raw in f:
  204. line = raw.strip()
  205. if not line or line.startswith("#"):
  206. continue
  207. return True
  208. return False
  209. except Exception:
  210. return False
  211. def _has_compatible_blocked_file_content(path: str, use_src: bool) -> bool:
  212. """Whether a value file is safe for the ACL representation being enabled.
  213. A plain username is not valid content for a Squid ``include`` file, and a
  214. source ACL directive is not an authenticated username. Do not activate a
  215. representation unless at least one valid entry already matches it.
  216. """
  217. blocked_usernames, _preserved_lines = _read_blocked_usernames(path, use_src)
  218. return bool(blocked_usernames)
  219. def _sync_blocked_file_to_docker(blocked_path: str) -> bool:
  220. """Copy the blocked-user list only to the selected Docker Squid runtime.
  221. A host can have both a local Squid binary and more than one Docker
  222. container. Do not use a hard-coded container name here: the quota ACL
  223. must be kept in sync with the same runtime selected for validation and
  224. reconfiguration.
  225. """
  226. runtime = _find_squid_runtime()
  227. if runtime is None or runtime.kind != "docker" or not runtime.container_name:
  228. logger.debug(
  229. "No se sincronizó %s por docker cp: el runtime Squid seleccionado no es Docker",
  230. blocked_path,
  231. )
  232. return False
  233. try:
  234. subprocess.run( # nosec B603 # noqa: S603
  235. [
  236. runtime.executable,
  237. "cp",
  238. blocked_path,
  239. f"{runtime.container_name}:{blocked_path}",
  240. ],
  241. check=True,
  242. capture_output=True,
  243. timeout=10,
  244. )
  245. return True
  246. except Exception as e:
  247. logger.debug("No se pudo sincronizar %s a Docker: %s", blocked_path, e)
  248. return False
  249. _SRC_BLOCK_ENTRY_RE = re.compile(
  250. r"^acl\s+usuarios_bloqueados\s+src\s+(\S+)\s*$", re.IGNORECASE
  251. )
  252. def _is_valid_src_value(value: str) -> bool:
  253. """Return whether an entry can safely be emitted in a ``src`` ACL.
  254. The quota table normally contains client IPs when proxy authentication is
  255. off. Treating an arbitrary username as an ACL value is unsafe: a newline
  256. or another Squid directive would turn the included value file into active
  257. configuration. Restrict this representation to IP addresses/networks,
  258. which is also what the ``src`` ACL accepts for this use case.
  259. """
  260. try:
  261. ipaddress.ip_network(value, strict=False)
  262. except ValueError:
  263. return False
  264. return True
  265. def _is_valid_proxy_auth_value(value: str) -> bool:
  266. """Return whether a value is safe as one line of a proxy_auth list."""
  267. return (
  268. bool(value) and "#" not in value and not any(char.isspace() for char in value)
  269. )
  270. def _is_preservable_blocked_file_line(raw_line: str) -> bool:
  271. """Keep comments/blank lines, but never incompatible list data.
  272. A source-format list is parsed as Squid configuration while a proxy-auth
  273. list is parsed as identities. Preserving arbitrary non-comment lines
  274. across a mode change was the root cause of malformed ``include`` files.
  275. """
  276. stripped = raw_line.strip()
  277. return not stripped or stripped.startswith("#")
  278. def _parse_blocked_file_line(raw_line: str, use_src: bool) -> str | None:
  279. """Parse one entry only when it belongs to the requested representation."""
  280. raw = raw_line.strip()
  281. if not raw or raw.startswith("#"):
  282. return None
  283. source_directive = _normalised_squid_line(raw)
  284. match = _SRC_BLOCK_ENTRY_RE.fullmatch(source_directive)
  285. if use_src:
  286. if match and _is_valid_src_value(match.group(1)):
  287. return match.group(1)
  288. return None
  289. # A previous IP-based representation is not a username. Dropping it is
  290. # safer than accidentally blocking a literal identity named ``acl`` (or
  291. # emitting a malformed source include on a later transition).
  292. if match:
  293. return None
  294. parts = [part.strip() for part in raw.split(" - ")]
  295. value = parts[1] if len(parts) > 1 else parts[0]
  296. return value if _is_valid_proxy_auth_value(value) else None
  297. def _read_blocked_usernames(
  298. file_path: str, use_src: bool
  299. ) -> tuple[set[str], list[str]]:
  300. blocked_usernames: set[str] = set()
  301. preserved_lines: list[str] = []
  302. if not os.path.exists(file_path):
  303. return blocked_usernames, preserved_lines
  304. try:
  305. with open(file_path, encoding="utf-8") as f:
  306. for raw_line in f:
  307. username = _parse_blocked_file_line(raw_line, use_src)
  308. if username is None:
  309. if _is_preservable_blocked_file_line(raw_line):
  310. preserved_lines.append(raw_line.rstrip("\n"))
  311. elif raw_line.strip():
  312. logger.warning(
  313. "Se descartó una entrada de cuota incompatible con el modo %s: %s",
  314. "src" if use_src else "proxy_auth",
  315. raw_line.strip(),
  316. )
  317. else:
  318. blocked_usernames.add(username)
  319. except Exception as e:
  320. logger.warning("No se pudo leer %s: %s", file_path, e)
  321. return blocked_usernames, preserved_lines
  322. def _render_block_entry(username: str, use_src: bool) -> str | None:
  323. """Render one safely validated quota value for the selected ACL mode."""
  324. value = str(username).strip()
  325. if use_src:
  326. if not _is_valid_src_value(value):
  327. logger.warning(
  328. "Se omitió una cuota sin IP/red válida para ACL src: %s", value
  329. )
  330. return None
  331. return f"acl usuarios_bloqueados src {value}"
  332. if not _is_valid_proxy_auth_value(value):
  333. logger.warning("Se omitió una identidad proxy_auth no válida: %s", value)
  334. return None
  335. return value
  336. def _render_block_entries(usernames: set[str], use_src: bool) -> list[str]:
  337. """Render a deterministic, validated complete quota list."""
  338. entries: list[str] = []
  339. for username in sorted({str(username) for username in usernames}):
  340. entry = _render_block_entry(username, use_src)
  341. if entry is not None:
  342. entries.append(entry)
  343. return entries
  344. def _build_blocked_users_file_content(
  345. file_path: str, usernames: set[str], use_src: bool
  346. ) -> tuple[str | None, set[str]]:
  347. """Build the complete target file without writing it.
  348. Returning ``None`` means the file should not exist. This makes an empty
  349. quota set an explicit state transition rather than a silently ignored
  350. deletion.
  351. """
  352. existing_blocked, preserved_lines = _read_blocked_usernames(file_path, use_src)
  353. output_lines = [*preserved_lines, *_render_block_entries(usernames, use_src)]
  354. if not output_lines:
  355. return None, existing_blocked
  356. return "\n".join(output_lines).rstrip() + "\n", existing_blocked
  357. def _sync_blocked_users_file(
  358. file_path: str, usernames: set[str], use_src: bool
  359. ) -> tuple[bool, set[str]]:
  360. new_content, existing_blocked = _build_blocked_users_file_content(
  361. file_path, usernames, use_src
  362. )
  363. if new_content is None:
  364. if os.path.exists(file_path):
  365. try:
  366. os.remove(file_path)
  367. return True, existing_blocked
  368. except Exception as e:
  369. logger.warning("No se pudo eliminar %s: %s", file_path, e)
  370. return False, existing_blocked
  371. try:
  372. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  373. if os.path.exists(file_path):
  374. with open(file_path, encoding="utf-8") as f:
  375. current_content = f.read()
  376. if current_content == new_content:
  377. return False, existing_blocked
  378. # Do not truncate a live value list. The same atomic replacement
  379. # primitive used for squid.conf preserves the old file until the new
  380. # complete representation is ready.
  381. SquidConfigManager._atomic_write(file_path, new_content)
  382. try:
  383. os.chmod(file_path, 0o640)
  384. except Exception as e:
  385. logger.warning("No se pudo fijar permisos en %s: %s", file_path, e)
  386. return True, existing_blocked
  387. except Exception as e:
  388. logger.warning("No se pudo escribir %s: %s", file_path, e)
  389. return False, existing_blocked
  390. def clear_blocked_users_file() -> None:
  391. """Elimina el archivo de usuarios bloqueados del sistema local.
  392. Debe llamarse cuando se vacía la lista de bloqueados (ej: reinicio mensual).
  393. Después de esta llamada, invocar _sync_quota_squid_rules(True) para que las
  394. directivas ACL se eliminen de squid.conf al detectar que el archivo no existe.
  395. """
  396. try:
  397. if os.path.exists(_BLOCKED_USERS_PATH):
  398. os.remove(_BLOCKED_USERS_PATH)
  399. logger.info(
  400. "Archivo de usuarios bloqueados eliminado: %s", _BLOCKED_USERS_PATH
  401. )
  402. else:
  403. logger.debug(
  404. "Archivo %s ya no existe, nada que eliminar", _BLOCKED_USERS_PATH
  405. )
  406. except Exception as e:
  407. logger.warning("No se pudo eliminar %s: %s", _BLOCKED_USERS_PATH, e)
  408. def _commit_modular_config(cm: SquidConfigManager, filename: str, lines: list[str]):
  409. content = "\n".join(line for line in lines if line.strip() != "")
  410. return cm.save_modular_config(filename, content)
  411. def _sync_quota_squid_rules(
  412. enabled: bool,
  413. *,
  414. blocked_file_ready: bool | None = None,
  415. before_validation: Callable[[], bool] | None = None,
  416. rollback_callback: Callable[[], None] | None = None,
  417. force_reload: bool = False,
  418. ) -> bool:
  419. """Sync `usuarios_bloqueados` ACL/http_access in Squid config.
  420. The optional callbacks are used by the scheduler's format transition:
  421. they keep the list-file update in the same write transaction as its ACL
  422. representation, and run it before validation/reconfigure.
  423. """
  424. cm = SquidConfigManager()
  425. if not cm.is_valid:
  426. return _sync_quota_squid_rules_locked(
  427. enabled,
  428. cm,
  429. blocked_file_ready=blocked_file_ready,
  430. before_validation=before_validation,
  431. rollback_callback=rollback_callback,
  432. force_reload=force_reload,
  433. )
  434. # Use the normalized path selected by the manager rather than the global
  435. # default. Installations may fall back from a stale environment path to
  436. # /etc/squid/squid.conf, which must share the same transaction lock as
  437. # Kerberos and the other configuration editors.
  438. with squid_config_write_lock(cm.config_path):
  439. if cm.load_config() is False:
  440. logger.error("No se pudo recargar squid.conf antes de sincronizar cuotas")
  441. return False
  442. refresh_layout = getattr(cm, "_check_modular_config", None)
  443. if callable(refresh_layout):
  444. refresh_layout()
  445. return _sync_quota_squid_rules_locked(
  446. enabled,
  447. cm,
  448. blocked_file_ready=blocked_file_ready,
  449. before_validation=before_validation,
  450. rollback_callback=rollback_callback,
  451. force_reload=force_reload,
  452. )
  453. def _sync_quota_squid_rules_locked(
  454. enabled: bool,
  455. cm: SquidConfigManager | None = None,
  456. *,
  457. blocked_file_ready: bool | None = None,
  458. before_validation: Callable[[], bool] | None = None,
  459. rollback_callback: Callable[[], None] | None = None,
  460. force_reload: bool = False,
  461. ) -> bool:
  462. """Perform one quota configuration transaction while holding the shared lock."""
  463. cm = cm or SquidConfigManager()
  464. logger.debug(
  465. "sync_quota_squid_rules: enabled={}, config_path={}, config_dir={}, is_modular={}, is_valid={}",
  466. enabled,
  467. cm.config_path,
  468. cm.config_dir,
  469. cm.is_modular,
  470. cm.is_valid,
  471. )
  472. if not cm.is_valid:
  473. logger.warning(
  474. "SquidConfigManager no válido: no se puede sincronizar reglas de cuota. Errores: {}",
  475. "; ".join(cm.errors) if cm.errors else "sin detalles",
  476. )
  477. return False
  478. if not _managed_kerberos_modular_layout_is_supported(cm):
  479. return False
  480. blocked_path = _BLOCKED_USERS_PATH
  481. def _is_acl_line(line: str) -> bool:
  482. return _is_quota_acl_entry(line, blocked_path)
  483. def _is_http_line(line: str) -> bool:
  484. return (
  485. _normalised_squid_line(line).casefold()
  486. == "http_access deny usuarios_bloqueados"
  487. )
  488. def _build_acl_line(use_src: bool) -> str:
  489. if use_src:
  490. return f"include {blocked_path}"
  491. # Squid treats a quoted path as an external ACL value file. Without
  492. # quotes it is merely one literal username equal to the path, so the
  493. # quota list would never be consulted.
  494. return f'acl usuarios_bloqueados proxy_auth -i "{blocked_path}"'
  495. auth_configured = cm.has_proxy_authentication()
  496. use_src = not auth_configured
  497. # The ACL is only safe to enable when the file already uses its selected
  498. # syntax. A transition supplies ``blocked_file_ready`` because it stages
  499. # the converted file inside this same transaction.
  500. if blocked_file_ready is None:
  501. blocked_file_ready = _has_compatible_blocked_file_content(blocked_path, use_src)
  502. enabled = enabled and blocked_file_ready
  503. logger.debug(
  504. "_sync_quota_squid_rules: blocked_path={}, should_enable_acl={}",
  505. blocked_path,
  506. enabled,
  507. )
  508. acl_line = _build_acl_line(use_src)
  509. http_line = "http_access deny usuarios_bloqueados"
  510. def _apply_changes(acl_line: str, http_line: str, use_src: bool) -> bool:
  511. previous_main_content = cm.config_content or ""
  512. previous_acls_content = ""
  513. previous_http_content = ""
  514. config_changed = False
  515. runtime = None
  516. reconfiguration_attempted = False
  517. try:
  518. if cm.is_modular:
  519. previous_acls_content = cm.read_modular_config("100_acls.conf") or ""
  520. previous_http_content = (
  521. cm.read_modular_config("120_http_access.conf") or ""
  522. )
  523. acls_content = previous_acls_content
  524. acl_lines = [
  525. line for line in acls_content.split("\n") if line.strip() != ""
  526. ]
  527. original_acl_lines = acl_lines.copy()
  528. # ``include ...usuarios_bloqueados`` and the proxy_auth ACL
  529. # are two encodings of the same generated policy. Remove
  530. # every prior encoding first, then add exactly the selected
  531. # one. Keeping an old include during a Kerberos transition
  532. # makes Squid parse plain identities as directives.
  533. acl_lines = [line for line in acl_lines if not _is_acl_line(line)]
  534. if enabled:
  535. if use_src:
  536. acl_lines.insert(0, acl_line)
  537. else:
  538. inserted = False
  539. for i, line in enumerate(acl_lines):
  540. if line.strip().startswith("acl "):
  541. acl_lines.insert(i, acl_line)
  542. inserted = True
  543. break
  544. if not inserted:
  545. acl_lines.append(acl_line)
  546. if acl_lines != original_acl_lines:
  547. config_changed = True
  548. if not _commit_modular_config(cm, "100_acls.conf", acl_lines):
  549. raise RuntimeError("No se pudieron guardar 100_acls.conf")
  550. http_content = previous_http_content
  551. http_lines = [
  552. line for line in http_content.split("\n") if line.strip() != ""
  553. ]
  554. original_http_lines = http_lines.copy()
  555. if enabled:
  556. http_lines = _ensure_quota_http_rule(
  557. http_lines, http_line, use_src=use_src
  558. )
  559. else:
  560. http_lines = [
  561. line for line in http_lines if not _is_http_line(line)
  562. ]
  563. if http_lines != original_http_lines:
  564. config_changed = True
  565. if not _commit_modular_config(cm, "120_http_access.conf", http_lines):
  566. raise RuntimeError("No se pudieron guardar 120_http_access.conf")
  567. else:
  568. if not cm.config_content and enabled:
  569. logger.error(
  570. "config_content está vacío (posible fallo de carga). "
  571. "Se cancela la modificación de squid.conf para evitar pérdida de datos."
  572. )
  573. return False
  574. lines = cm.config_content.split("\n") if cm.config_content else []
  575. original_lines = lines.copy()
  576. # See the modular branch above: migration is replacement,
  577. # not addition. This also cleans older direct ``src`` ACLs
  578. # generated by previous releases.
  579. lines = [line for line in lines if not _is_acl_line(line)]
  580. if enabled:
  581. if use_src:
  582. insert_idx = 0
  583. for i, line in enumerate(lines):
  584. if line.strip() and not line.strip().startswith("#"):
  585. insert_idx = i
  586. break
  587. lines.insert(insert_idx, acl_line)
  588. else:
  589. inserted = False
  590. for i, line in enumerate(lines):
  591. if line.strip().startswith(
  592. "acl "
  593. ) or line.strip().startswith("http_access "):
  594. lines.insert(i, acl_line)
  595. inserted = True
  596. break
  597. if not inserted:
  598. lines.append(acl_line)
  599. lines = _ensure_quota_http_rule(lines, http_line, use_src=use_src)
  600. else:
  601. lines = [line for line in lines if not _is_http_line(line)]
  602. if lines != original_lines:
  603. config_changed = True
  604. if not cm.save_config("\n".join(lines)):
  605. raise RuntimeError("No se pudo guardar squid.conf")
  606. # A proxy-auth transition first switches the ACL representation,
  607. # then writes its value list here, before Squid can validate or
  608. # reload it. Conversely, src transitions stage the value file
  609. # before calling this transaction. Both paths therefore avoid
  610. # exposing a plain username as an ``include`` directive.
  611. if before_validation is not None and not before_validation():
  612. raise RuntimeError(
  613. "No se pudo preparar el archivo de bloqueados para la transición de cuotas"
  614. )
  615. if not config_changed and not force_reload:
  616. return True
  617. splitter = SquidConfigSplitter(
  618. input_file=cm.config_path,
  619. output_dir=cm.config_dir,
  620. )
  621. runtime = _find_squid_runtime()
  622. if runtime is None:
  623. raise RuntimeError(
  624. "No se encontró el runtime Squid correcto para validar y recargar cuotas."
  625. )
  626. validation = splitter._validate_squid_config()
  627. if not validation.get("success"):
  628. raise RuntimeError(
  629. "Validación de Squid falló al sincronizar reglas de cuota: "
  630. f"{validation.get('error_message') or validation.get('output') or '<sin detalles>'}"
  631. )
  632. reconfiguration_attempted = True
  633. reload_success, reload_msg = reconfigure_squid(cm.config_path, runtime)
  634. if not reload_success:
  635. raise RuntimeError(
  636. "Squid no se pudo recargar después de actualizar reglas de cuota: "
  637. f"{reload_msg}"
  638. )
  639. logger.info("Squid recargado correctamente")
  640. return True
  641. except Exception:
  642. logger.exception("Error aplicando reglas de cuota")
  643. if cm.is_modular:
  644. cm.save_modular_config("100_acls.conf", previous_acls_content)
  645. cm.save_modular_config("120_http_access.conf", previous_http_content)
  646. if previous_main_content:
  647. cm.save_config(previous_main_content)
  648. if rollback_callback is not None:
  649. try:
  650. rollback_callback()
  651. except Exception as rollback_error:
  652. logger.error(
  653. "No se pudo restaurar el archivo de cuotas tras un fallo: {}",
  654. rollback_error,
  655. )
  656. if reconfiguration_attempted and runtime is not None:
  657. restored, restore_message = reconfigure_squid(cm.config_path, runtime)
  658. if not restored:
  659. logger.error(
  660. "No se pudo recargar Squid tras restaurar cuotas: {}",
  661. restore_message,
  662. )
  663. return False
  664. ok = _apply_changes(acl_line, http_line, use_src)
  665. if not ok:
  666. logger.error(
  667. "No se pudo sincronizar las reglas de cuota. use_src={}, acl_line={}, http_line={}",
  668. use_src,
  669. acl_line,
  670. http_line,
  671. )
  672. return ok
  673. def _blocked_users_file_snapshot(file_path: str) -> tuple[bool, str | None, int | None]:
  674. """Capture the managed list before a config/list transition."""
  675. if not os.path.exists(file_path):
  676. return False, None, None
  677. with open(file_path, encoding="utf-8") as current_file:
  678. content = current_file.read()
  679. return True, content, os.stat(file_path).st_mode & 0o777
  680. def _restore_blocked_users_file(
  681. file_path: str, snapshot: tuple[bool, str | None, int | None]
  682. ) -> None:
  683. """Restore a value-list snapshot after a failed quota transaction."""
  684. existed, content, mode = snapshot
  685. if not existed:
  686. if os.path.exists(file_path):
  687. os.remove(file_path)
  688. return
  689. if content is None:
  690. raise RuntimeError("Snapshot de cuotas incompleto")
  691. SquidConfigManager._atomic_write(file_path, content)
  692. if mode is not None:
  693. os.chmod(file_path, mode)
  694. def _sync_blocked_file_to_selected_runtime(blocked_path: str) -> bool:
  695. """Copy a changed value file when the selected Squid runtime is Docker."""
  696. runtime = _find_squid_runtime()
  697. if runtime is None or getattr(runtime, "kind", None) != "docker":
  698. return True
  699. return _sync_blocked_file_to_docker(blocked_path)
  700. def _sync_blocked_users_and_squid_rules(
  701. file_path: str, usernames: set[str]
  702. ) -> tuple[bool, set[str]]:
  703. """Atomically transition the quota list and its Squid representation.
  704. The returned boolean reports a fully committed state, not merely whether
  705. the file content changed. The source representation (an ``include`` of
  706. ACL directives) cannot read a plain proxy-auth list. The reverse is
  707. syntactically safe, so a move to
  708. ``proxy_auth`` switches the config first and writes the list immediately
  709. before validation/reload. A move back to ``src`` writes valid ACL
  710. directives first and only then enables the include. All writes share the
  711. Squid configuration lock and restore both files on failure.
  712. """
  713. cm = SquidConfigManager()
  714. if not cm.is_valid:
  715. logger.warning(
  716. "SquidConfigManager no válido: no se puede sincronizar el estado de cuotas"
  717. )
  718. return False, set()
  719. with squid_config_write_lock(cm.config_path):
  720. if cm.load_config() is False:
  721. logger.error(
  722. "No se pudo recargar squid.conf antes de migrar el archivo de cuotas"
  723. )
  724. return False, set()
  725. refresh_layout = getattr(cm, "_check_modular_config", None)
  726. if callable(refresh_layout):
  727. refresh_layout()
  728. use_src = not cm.has_proxy_authentication()
  729. try:
  730. snapshot = _blocked_users_file_snapshot(file_path)
  731. planned_content, existing_blocked = _build_blocked_users_file_content(
  732. file_path, usernames, use_src
  733. )
  734. except OSError as exc:
  735. logger.warning(
  736. "No se pudo preparar la transición del archivo de cuotas %s: %s",
  737. file_path,
  738. exc,
  739. )
  740. return False, set()
  741. existed, previous_content, _mode = snapshot
  742. file_will_change = (not existed and planned_content is not None) or (
  743. existed and previous_content != planned_content
  744. )
  745. blocked_file_ready = bool(_render_block_entries(usernames, use_src))
  746. file_changed = False
  747. restored = False
  748. def restore_file() -> None:
  749. nonlocal restored
  750. if restored:
  751. return
  752. _restore_blocked_users_file(file_path, snapshot)
  753. if snapshot[0]:
  754. _sync_blocked_file_to_selected_runtime(file_path)
  755. restored = True
  756. def stage_file() -> bool:
  757. nonlocal file_changed
  758. file_changed, _unused_existing = _sync_blocked_users_file(
  759. file_path, usernames, use_src
  760. )
  761. if not file_changed:
  762. return not file_will_change
  763. if (
  764. planned_content is not None
  765. and not _sync_blocked_file_to_selected_runtime(file_path)
  766. ):
  767. logger.error(
  768. "No se pudo sincronizar el archivo de cuotas al runtime Docker seleccionado"
  769. )
  770. return False
  771. return True
  772. if use_src:
  773. # A source include must never see a plain identity line. Stage
  774. # its ACL-format list before adding/replacing the include.
  775. if not stage_file():
  776. restore_file()
  777. return False, existing_blocked
  778. ok = _sync_quota_squid_rules_locked(
  779. True,
  780. cm,
  781. blocked_file_ready=blocked_file_ready,
  782. rollback_callback=restore_file,
  783. force_reload=file_changed,
  784. )
  785. else:
  786. # Switching source -> proxy_auth is safe only after the include
  787. # is removed. Stage the plain list after that replacement but
  788. # before validation/reconfigure.
  789. ok = _sync_quota_squid_rules_locked(
  790. True,
  791. cm,
  792. blocked_file_ready=blocked_file_ready,
  793. before_validation=stage_file,
  794. rollback_callback=restore_file,
  795. force_reload=file_will_change,
  796. )
  797. if not ok:
  798. restore_file()
  799. return ok, existing_blocked