test_searxng_workload.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The SearXNG workload (issue #425): a compose definition that is pinned, private, limited and holds no secret.
  3. workloads/searxng/ is a documented, unapplied stage 3 workload. Nothing here starts a container or reads the
  4. network. A mutable tag, a published cache, a wildcard bind, a secret value in a file, a limiter that is off or a
  5. public instance flag would each make a private search proxy into something else, so each guard has a negative case.
  6. """
  7. import re
  8. import subprocess
  9. import tomllib
  10. from pathlib import Path
  11. import yaml
  12. ROOT = Path(__file__).resolve().parent.parent
  13. DIR = ROOT / "workloads" / "searxng"
  14. COMPOSE = DIR / "docker-compose.yml"
  15. SETTINGS = DIR / "settings.yml"
  16. LIMITER = DIR / "limiter.toml"
  17. ENV_EXAMPLE = DIR / "env.example"
  18. README = DIR / "README.md"
  19. PINNED = re.compile(r"^[a-z0-9./_-]+:[A-Za-z0-9._-]+@sha256:[0-9a-f]{64}$")
  20. MUTABLE_TAGS = {"latest", "stable", "main", "master", "edge", "unstable"}
  21. WILDCARD = re.compile(r"(^|[:\s\"'])(0\.0\.0\.0|\[::\]|::)([:\s\"']|$)")
  22. # A bind is acceptable only as a required variable (compose stops if it is unset) or a literal private address.
  23. BIND_OK = re.compile(r"^(\$\{[A-Z_]+:\?[^}]*\}|10\.\d+\.\d+\.\d+|192\.168\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+):\d+:\d+$")
  24. SECRET_NAME = re.compile(r"(SECRET|PASSWORD|PASSWD|TOKEN|API_?KEY|PRIVATE_?KEY)", re.IGNORECASE)
  25. REQUIRED_VAR = re.compile(r"^\$\{[A-Z_]+:\?[^}]*\}$")
  26. PLACEHOLDER = re.compile(r"(replaced|placeholder|changeme|change-me|set-by|from-the-environment)", re.IGNORECASE)
  27. def load(path: Path = COMPOSE) -> dict:
  28. return yaml.safe_load(path.read_text(encoding="utf-8"))
  29. def images(compose: dict) -> list[str]:
  30. return [s["image"] for s in compose["services"].values()]
  31. def unpinned(compose: dict) -> list[str]:
  32. bad = []
  33. for ref in images(compose):
  34. tag = ref.split("@")[0].rsplit(":", 1)[-1]
  35. if not PINNED.match(ref) or tag in MUTABLE_TAGS:
  36. bad.append(ref)
  37. return bad
  38. def port_problems(compose: dict) -> list[str]:
  39. bad = []
  40. for name, svc in compose["services"].items():
  41. for p in svc.get("ports", []):
  42. p = p if isinstance(p, str) else str(p)
  43. if WILDCARD.search(p) or not BIND_OK.match(p):
  44. bad.append(f"{name}: {p}")
  45. return bad
  46. def cache_problems(compose: dict) -> list[str]:
  47. bad = []
  48. for name, svc in compose["services"].items():
  49. if "valkey" in svc["image"] or "redis" in svc["image"]:
  50. if svc.get("ports"):
  51. bad.append(f"{name} publishes ports")
  52. if "network_mode" in svc:
  53. bad.append(f"{name} sets network_mode")
  54. nets = svc.get("networks", [])
  55. if not nets or any(not compose["networks"][n].get("internal") for n in nets):
  56. bad.append(f"{name} is on a network that is not internal")
  57. for p in svc.get("ports", []):
  58. if "6379" in str(p):
  59. bad.append(f"{name} publishes 6379")
  60. return bad
  61. def secret_value_problems(compose: dict) -> list[str]:
  62. """Any environment value whose name looks secret must be a required variable (or empty), never a literal."""
  63. bad = []
  64. for name, svc in compose["services"].items():
  65. env = svc.get("environment", {})
  66. if isinstance(env, list):
  67. env = dict(e.split("=", 1) for e in env)
  68. for key, val in env.items():
  69. if SECRET_NAME.search(key) and val not in (None, "") and not REQUIRED_VAR.match(str(val)):
  70. bad.append(f"{name}.{key}")
  71. return bad
  72. def env_file_problems(text: str) -> list[str]:
  73. bad = []
  74. for line in text.splitlines():
  75. s = line.strip()
  76. if not s or s.startswith("#") or "=" not in s:
  77. continue
  78. key, val = s.split("=", 1)
  79. if SECRET_NAME.search(key) and val.strip().strip("\"'") != "":
  80. bad.append(key)
  81. return bad
  82. def settings_problems(settings: dict) -> list[str]:
  83. bad = []
  84. server = settings.get("server", {})
  85. if server.get("limiter") is not True:
  86. bad.append("server.limiter is not true")
  87. if server.get("public_instance") is not False:
  88. bad.append("server.public_instance is not false")
  89. if not str(settings.get("valkey", {}).get("url", "")).startswith("valkey://"):
  90. bad.append("valkey.url is missing (the limiter needs it)")
  91. key = str(server.get("secret_key", ""))
  92. if key == "ultrasecretkey" or not PLACEHOLDER.search(key):
  93. bad.append("server.secret_key is not a placeholder")
  94. out = settings.get("outgoing", {}) or {}
  95. if out.get("proxies") or out.get("using_tor_proxy"):
  96. bad.append("an outgoing proxy is on by default")
  97. return bad
  98. def env_override_problems(compose: dict) -> list[str]:
  99. """The environment overrides the file in SearXNG, so it must not switch the guards off."""
  100. bad = []
  101. for name, svc in compose["services"].items():
  102. env = svc.get("environment", {}) or {}
  103. if isinstance(env, list):
  104. env = dict(e.split("=", 1) for e in env)
  105. if str(env.get("SEARXNG_LIMITER", "true")).lower() not in ("true", "1"):
  106. bad.append(f"{name}: SEARXNG_LIMITER is off")
  107. if str(env.get("SEARXNG_PUBLIC_INSTANCE", "false")).lower() not in ("false", "0"):
  108. bad.append(f"{name}: SEARXNG_PUBLIC_INSTANCE is on")
  109. return bad
  110. # ---- the real files -------------------------------------------------------------------------------------------
  111. def test_the_workload_files_exist():
  112. for p in (COMPOSE, SETTINGS, LIMITER, ENV_EXAMPLE, README):
  113. assert p.is_file(), p
  114. def test_the_compose_file_parses_and_has_the_services():
  115. compose = load()
  116. assert set(compose["services"]) == {"core", "valkey", "bind-check"}
  117. assert compose["networks"]["backend"]["internal"] is True
  118. def test_every_image_is_pinned_by_tag_and_digest():
  119. refs = images(load())
  120. assert len(refs) == 3, "the guard collected too little"
  121. assert not unpinned(load()), unpinned(load())
  122. # ---- the bind check: a pre-start step that refuses an address that is not private ------------------------------
  123. def bind_check_script(compose: dict) -> str:
  124. """The shell text the bind-check service runs, as the shell sees it ($$ is compose's escape for $)."""
  125. entry = compose["services"]["bind-check"]["entrypoint"]
  126. assert entry[:2] == ["/bin/sh", "-c"] and len(entry) == 3, entry
  127. return entry[2].replace("$$", "$")
  128. def run_bind_check(script: str, value: str) -> int:
  129. done = subprocess.run(["/bin/sh", "-c", script], check=False, env={"SEARXNG_BIND": value, "PATH": "/usr/bin:/bin"}, capture_output=True, text=True, timeout=10)
  130. return done.returncode
  131. def bind_check_wiring_problems(compose: dict) -> list[str]:
  132. bad = []
  133. svc = compose["services"].get("bind-check")
  134. if svc is None:
  135. return ["no bind-check service"]
  136. if "restart" not in svc or str(svc["restart"]).strip('"') != "no":
  137. bad.append("bind-check restarts")
  138. if not REQUIRED_VAR.match(str(svc.get("environment", {}).get("SEARXNG_BIND", ""))):
  139. bad.append("bind-check does not require SEARXNG_BIND")
  140. if svc.get("ports"):
  141. bad.append("bind-check publishes ports")
  142. deps = compose["services"]["core"].get("depends_on", {})
  143. if not isinstance(deps, dict) or deps.get("bind-check", {}).get("condition") != "service_completed_successfully":
  144. bad.append("core does not wait for bind-check to complete successfully")
  145. return bad
  146. PRIVATE_BINDS = ("10.116.0.5", "10.0.0.1", "192.168.1.20", "172.16.0.2", "172.31.255.1", "127.0.0.1")
  147. REFUSED_BINDS = (
  148. "0.0.0.0",
  149. "::",
  150. "[::]",
  151. "",
  152. "8.8.8.8",
  153. "172.15.0.1",
  154. "172.32.0.1",
  155. "192.169.0.1",
  156. "100.64.0.1",
  157. "10.0.0.1:9999",
  158. "10.0.0.1 ",
  159. "10.0.0.1,0.0.0.0",
  160. "10.example.com",
  161. "localhost",
  162. )
  163. def test_the_bind_check_accepts_private_addresses_and_refuses_the_rest():
  164. script = bind_check_script(load())
  165. for value in PRIVATE_BINDS:
  166. assert run_bind_check(script, value) == 0, value
  167. for value in REFUSED_BINDS:
  168. assert run_bind_check(script, value) != 0, repr(value)
  169. def test_the_bind_check_blocks_core_and_publishes_nothing():
  170. assert bind_check_wiring_problems(load()) == []
  171. def test_the_bind_check_guard_bites():
  172. compose = load()
  173. script = bind_check_script(compose)
  174. # A check that accepts everything, or one that lets a wildcard through, fails the refused list.
  175. assert run_bind_check("exit 0", "0.0.0.0") == 0
  176. loose = script.replace("10.*", "*", 1)
  177. assert loose != script and run_bind_check(loose, "0.0.0.0") == 0
  178. # The wiring guard sees each way of letting core start without the check.
  179. for mutate in (
  180. lambda c: c["services"]["core"].update(depends_on={"valkey": {"condition": "service_started"}}),
  181. lambda c: c["services"]["core"].update(depends_on=["valkey", "bind-check"]),
  182. lambda c: c["services"]["core"]["depends_on"]["bind-check"].update(condition="service_started"),
  183. lambda c: c["services"]["bind-check"].update(restart="unless-stopped"),
  184. lambda c: c["services"]["bind-check"]["environment"].update(SEARXNG_BIND="10.0.0.1"),
  185. lambda c: c["services"]["bind-check"].update(ports=["10.0.0.1:1:1"]),
  186. lambda c: c["services"].pop("bind-check"),
  187. ):
  188. bad = yaml.safe_load(yaml.safe_dump(compose))
  189. mutate(bad)
  190. assert bind_check_wiring_problems(bad), mutate
  191. def test_the_pins_guard_bites():
  192. good = {"services": {"a": {"image": "docker.io/x/y:1.2.3@sha256:" + "a" * 64}}}
  193. assert not unpinned(good)
  194. assert unpinned({"services": {"a": {"image": "docker.io/x/y:latest"}}})
  195. assert unpinned({"services": {"a": {"image": "docker.io/x/y:1.2.3"}}})
  196. assert unpinned({"services": {"a": {"image": "docker.io/x/y@sha256:" + "a" * 64}}})
  197. assert unpinned({"services": {"a": {"image": "docker.io/x/y:latest@sha256:" + "a" * 64}}})
  198. def test_every_published_port_is_bound_to_the_private_address():
  199. compose = load()
  200. published = [p for s in compose["services"].values() for p in s.get("ports", [])]
  201. assert len(published) == 1, "the guard collected the wrong number of ports"
  202. assert not port_problems(compose)
  203. assert not WILDCARD.search(COMPOSE.read_text(encoding="utf-8"))
  204. def test_the_port_guard_bites():
  205. def one(p: str) -> dict:
  206. return {"services": {"core": {"image": "x", "ports": [p]}}}
  207. assert not port_problems(one("${SEARXNG_BIND:?set the private address}:8080:8080"))
  208. assert not port_problems(one("10.116.0.5:8080:8080"))
  209. for bad in ("8080:8080", "0.0.0.0:8080:8080", "[::]:8080:8080", ":::8080:8080", "${SEARXNG_BIND:-0.0.0.0}:8080:8080", "127.0.0.1:8080:8080x"):
  210. assert port_problems(one(bad)), bad
  211. assert WILDCARD.search("0.0.0.0:8080:8080")
  212. def test_the_cache_is_not_published_and_sits_on_an_internal_network():
  213. compose = load()
  214. assert "valkey" in compose["services"]["valkey"]["image"], "the guard collected nothing"
  215. assert not cache_problems(compose)
  216. def test_the_cache_guard_bites():
  217. base = {"networks": {"backend": {"internal": True}, "open": {}}}
  218. ok = {"services": {"v": {"image": "valkey/valkey:1@sha256:x", "networks": ["backend"]}}, **base}
  219. assert not cache_problems(ok)
  220. published = {"services": {"v": {"image": "valkey/valkey:1", "networks": ["backend"], "ports": ["10.0.0.1:6379:6379"]}}, **base}
  221. assert cache_problems(published)
  222. exposed = {"services": {"v": {"image": "valkey/valkey:1", "networks": ["open"]}}, **base}
  223. assert cache_problems(exposed)
  224. host_net = {"services": {"v": {"image": "valkey/valkey:1", "network_mode": "host", "networks": ["backend"]}}, **base}
  225. assert cache_problems(host_net)
  226. redis = {"services": {"v": {"image": "redis:7", "ports": ["6379:6379"]}}, **base}
  227. assert cache_problems(redis)
  228. def test_no_secret_value_is_in_any_workload_file():
  229. compose = load()
  230. assert not secret_value_problems(compose)
  231. assert "SEARXNG_SECRET" in str(compose["services"]["core"]["environment"]), "the guard collected nothing"
  232. assert REQUIRED_VAR.match(compose["services"]["core"]["environment"]["SEARXNG_SECRET"])
  233. assert not env_file_problems(ENV_EXAMPLE.read_text(encoding="utf-8"))
  234. settings = load(SETTINGS)
  235. assert PLACEHOLDER.search(settings["server"]["secret_key"])
  236. for p in (COMPOSE, SETTINGS, LIMITER, ENV_EXAMPLE):
  237. assert "ultrasecretkey" not in p.read_text(encoding="utf-8"), p
  238. def test_the_secret_guard_bites():
  239. bad = {"services": {"core": {"image": "x", "environment": {"SEARXNG_SECRET": "z" * 32}}}}
  240. assert secret_value_problems(bad) == ["core.SEARXNG_SECRET"]
  241. as_list = {"services": {"core": {"image": "x", "environment": ["DB_PASSWORD=hunter2hunter2"]}}}
  242. assert secret_value_problems(as_list) == ["core.DB_PASSWORD"]
  243. assert not secret_value_problems({"services": {"core": {"image": "x", "environment": {"SEARXNG_SECRET": "${SEARXNG_SECRET:?set it}"}}}})
  244. assert env_file_problems("SEARXNG_SECRET=" + "z" * 16 + "\n") == ["SEARXNG_SECRET"]
  245. assert not env_file_problems("# SEARXNG_SECRET=abc\nSEARXNG_SECRET=\n")
  246. def test_the_settings_file_has_the_limiter_on_and_the_instance_not_public():
  247. settings = load(SETTINGS)
  248. assert settings["server"]["limiter"] is True, "the guard collected nothing"
  249. assert not settings_problems(settings)
  250. assert not env_override_problems(load())
  251. def test_the_settings_guard_bites():
  252. good = load(SETTINGS)
  253. for path, value, needle in (
  254. (("server", "limiter"), False, "limiter"),
  255. (("server", "public_instance"), True, "public_instance"),
  256. (("server", "secret_key"), "ultrasecretkey", "secret_key"),
  257. (("server", "secret_key"), "k3J9xQ2mZ8vL5nR7", "secret_key"),
  258. ):
  259. bad = yaml.safe_load(yaml.safe_dump(good))
  260. bad[path[0]][path[1]] = value
  261. assert any(needle in p for p in settings_problems(bad)), path
  262. no_valkey = yaml.safe_load(yaml.safe_dump(good))
  263. no_valkey["valkey"] = {"url": False}
  264. assert any("valkey" in p for p in settings_problems(no_valkey))
  265. tor = yaml.safe_load(yaml.safe_dump(good))
  266. tor["outgoing"] = {"using_tor_proxy": True}
  267. assert any("proxy" in p for p in settings_problems(tor))
  268. def test_the_environment_cannot_switch_the_guards_off():
  269. off = {"services": {"core": {"image": "x", "environment": {"SEARXNG_LIMITER": "false"}}}}
  270. assert env_override_problems(off)
  271. public = {"services": {"core": {"image": "x", "environment": ["SEARXNG_PUBLIC_INSTANCE=true"]}}}
  272. assert env_override_problems(public)
  273. assert not env_override_problems({"services": {"core": {"image": "x", "environment": {"SEARXNG_LIMITER": "true"}}}})
  274. def test_the_limiter_file_parses_and_trusts_no_private_range_as_a_proxy():
  275. cfg = tomllib.loads(LIMITER.read_text(encoding="utf-8"))
  276. trusted = cfg["botdetection"]["trusted_proxies"]
  277. assert trusted, "the guard collected nothing"
  278. assert set(trusted) <= {"127.0.0.0/8", "::1"}, trusted
  279. assert cfg["botdetection"]["ip_limit"]["link_token"] is False
  280. assert cfg["botdetection"]["ip_lists"]["pass_searxng_org"] is False
  281. def test_the_tor_proxy_is_a_documented_option_and_off_by_default():
  282. text = SETTINGS.read_text(encoding="utf-8")
  283. assert "socks5h://" in text and "using_tor_proxy" in text, "the option is not documented in the settings file"
  284. assert not (load(SETTINGS).get("outgoing") or {}).get("proxies")
  285. assert not any("tor" in name for name in load()["services"])
  286. readme = README.read_text(encoding="utf-8")
  287. assert "off by default" in readme and "socks5h" in readme
  288. def test_both_services_have_a_memory_limit_and_no_new_privileges():
  289. for name, svc in load()["services"].items():
  290. assert "mem_limit" in svc, name
  291. assert "no-new-privileges:true" in svc.get("security_opt", []), name
  292. def test_the_readme_says_nothing_was_applied_and_links_the_lesson():
  293. readme = README.read_text(encoding="utf-8")
  294. assert "Not applied" in readme and "Not verified" in readme
  295. assert "Self-Hosting" in readme
  296. for needle in ("2026-11-01", "sha256:", "Twingate", "Portainer"):
  297. assert needle in readme, needle
  298. def test_the_digests_in_the_readme_match_the_compose_file():
  299. digests = {ref.split("@")[1] for ref in images(load())}
  300. readme = README.read_text(encoding="utf-8")
  301. assert len(digests) == 2
  302. for d in digests:
  303. assert d in readme, d