test_self_hosting_lesson.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The self-hosting lesson with SearXNG as the worked example (issue #424): registered, sourced, honest, safe to follow.
  3. docs/wiki/Self-Hosting-When-and-Why-with-SearXNG-as-the-Worked-Example.md teaches the trade of running a service
  4. yourself, who sees a query on each path, and a local lab. A banner that claims more than was run, a dead link, a
  5. missing registration, a real address, a lab command that binds to every address, a named public instance, a figure
  6. for memory that no source gave, or a claim with no status would each teach or reveal the wrong thing.
  7. """
  8. import re
  9. from pathlib import Path
  10. from wikitext import page_text
  11. ROOT = Path(__file__).resolve().parent.parent
  12. WIKI = ROOT / "docs" / "wiki"
  13. NAME = "Self-Hosting-When-and-Why-with-SearXNG-as-the-Worked-Example"
  14. PAGE = WIKI / f"{NAME}.md"
  15. LINK = re.compile(r"\]\(([A-Za-z0-9_-]+)\.md(?:#[^)]*)?\)")
  16. ADDR = re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
  17. ALLOWED_ADDR = re.compile(r"^(?:127\.0\.0\.1|192\.0\.2\.\d{1,3}|198\.51\.100\.\d{1,3}|203\.0\.113\.\d{1,3})$")
  18. STATUS_WORDS = ("Read", "General knowledge", "**est.**", "Observed", "Not run")
  19. URL = re.compile(r"https://([a-z0-9.-]+)(/[^)\s`]*)?")
  20. ALLOWED_HOSTS = {"docs.searxng.org", "docs.docker.com", "github.com", "raw.githubusercontent.com", "hub.docker.com", "auth.docker.io", "registry-1.docker.io"}
  21. DIAGRAM = re.compile(
  22. r"!\[(?P<alt>[^\]\n]*)\]\((?P<path>images/[^)\n]+\.png)\)\n\n<details>\n<summary>Diagram source \(Mermaid\)</summary>"
  23. r"\n\n```mermaid\n(?P<src>.*?)\n```\n\n</details>",
  24. re.DOTALL,
  25. )
  26. IMAGE_ANY = re.compile(r"!\[[^\]\n]*\]\([^)\n]+\)")
  27. PATH = re.compile(r"`((?:workloads|stacks|modules|scripts|tests|docs/stages|docs/superpowers)/[A-Za-z0-9_./-]+)`")
  28. FENCE = re.compile(r"^```(\w*)\n(.*?)^```$", re.MULTILINE | re.DOTALL)
  29. MAX_ALT = 150
  30. EXPECTED_DIAGRAMS = 2
  31. DATE_READ = "2026-11-01"
  32. PRICE = re.compile(r"[$]\s?\d|\b\d+\s?(?:dollars|USD|EUR)\b|\b(?:cheap|cheaper|cheapest|free of charge)\b|per month", re.IGNORECASE)
  33. def text() -> str:
  34. return page_text(PAGE) # without the generated navigation blocks (issue #417)
  35. def register_rows(body: str) -> list[list[str]]:
  36. reg = body.split("## Claims register")[1].split("\n## ")[0]
  37. rows = [line for line in reg.splitlines() if line.startswith("|") and not line.startswith("|---")]
  38. return [[c.strip() for c in r.strip("|").split("|")] for r in rows[1:]]
  39. def rows_missing_status(body: str) -> list[str]:
  40. return [r[0] for r in register_rows(body) if not any(w in r[-1] for w in STATUS_WORDS)]
  41. def stray_addresses(body: str) -> list[str]:
  42. return [a for a in ADDR.findall(body) if not ALLOWED_ADDR.match(a)]
  43. def foreign_hosts(body: str) -> list[str]:
  44. return sorted({h for h, _ in URL.findall(body) if h not in ALLOWED_HOSTS})
  45. def wildcard_binds(code: str) -> list[str]:
  46. return [ln for ln in code.splitlines() if re.search(r"0\.0\.0\.0|\[::\]|SEARXNG_BIND=\s*$|-p\s+\d+:\d+|--publish\s+\d+:\d+", ln)]
  47. def diagram_problems(body: str, wiki: Path = WIKI) -> list[str]:
  48. problems = []
  49. wrapped = list(DIAGRAM.finditer(body))
  50. if len(wrapped) != len(IMAGE_ANY.findall(body)):
  51. problems.append("a picture on the page is not a wrapped diagram")
  52. for m in wrapped:
  53. alt = m["alt"].strip()
  54. if len(alt) < 20 or len(alt) > MAX_ALT:
  55. problems.append(f"alt text length {len(alt)}: {alt[:40]!r}")
  56. if not m["src"].strip():
  57. problems.append(f"empty source for {m['path']}")
  58. if not (wiki / m["path"]).is_file():
  59. problems.append(f"picture missing: {m['path']}")
  60. return problems
  61. def test_the_banner_says_it_was_written_from_reading_and_nothing_was_deployed():
  62. body = text()
  63. assert body.startswith("# Self-hosting: when and why, with SearXNG as the worked example")
  64. assert "Status: unverified draft" in body
  65. assert "**Not run:**" in body and DATE_READ in body
  66. assert "## Not verified, plainly" in body
  67. assert "Docker Engine" in body.split("**Not run:**")[1].split("\n")[0]
  68. def test_every_linked_wiki_page_exists_and_the_required_lessons_are_linked():
  69. links = set(LINK.findall(text()))
  70. assert len(links) >= 10, "the guard collected too few links"
  71. assert not sorted(t for t in links if not (WIKI / f"{t}.md").exists())
  72. required = {
  73. "Containers-and-Docker-Basics",
  74. "How-a-VPN-Works-Tunnels-What-It-Hides-What-It-Does-Not-and-What-an-Audit-Proves",
  75. "How-Tor-Works-in-Depth-Circuits-Relays-Directory-Authorities-and-Onion-Services",
  76. "Privacy-Security-and-Anonymity-Three-Different-Things-and-Why-There-Is-No-Silver-Bullet",
  77. "Backups-Recovery-and-Patching",
  78. "The-DMZ-and-Hardening-a-Host-That-Faces-the-Internet",
  79. "Attack-Surface-List-Shrink-Measure",
  80. "Grafana-Basics-From-a-Blank-Page",
  81. "Detection-and-Monitoring-Wazuh-and-the-Landscape",
  82. }
  83. assert required <= links, sorted(required - links)
  84. def test_the_lesson_is_registered_everywhere_with_three_to_six_related_pages():
  85. nav = (WIKI / "_nav.yaml").read_text(encoding="utf-8")
  86. line = next(ln for ln in nav.splitlines() if f"page: {NAME}," in ln)
  87. assert 'status: "draft"' in line and "subgroup: \"Stage guides and design\"" in line
  88. related = re.search(r"related: \[([^\]]*)\]", line)
  89. assert related, "the nav entry has no related list"
  90. names = [n.strip() for n in related[1].split(",") if n.strip()]
  91. assert 3 <= len(names) <= 6, names
  92. for n in names:
  93. assert f"page: {n}," in nav, n
  94. for special in ("Contents.md", "_Sidebar.md", "Reading-Order.md"):
  95. assert f"{NAME}.md" in (WIKI / special).read_text(encoding="utf-8"), special
  96. rows = [ln for ln in (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines() if f"{NAME}.md" in ln]
  97. assert len(rows) >= 5, "expected glossary rows for the new terms"
  98. def test_glossary_rows_point_at_real_headings_and_no_term_is_duplicated():
  99. heads = {re.sub(r"[^a-z0-9-]", "", re.sub(r"[^a-z0-9 -]", "", h.lower()).strip().replace(" ", "-")) for h in re.findall(r"^#+ (.+)$", text(), re.MULTILINE)}
  100. gloss = (WIKI / "Glossary.md").read_text(encoding="utf-8").splitlines()
  101. anchors = set()
  102. for line in gloss:
  103. anchors.update(re.findall(rf"{NAME}\.md#([a-z0-9-]+)", line))
  104. assert anchors, "the guard collected nothing"
  105. assert anchors <= heads, sorted(anchors - heads)
  106. terms = [re.match(r"\| \*\*(.+?)\*\*", ln)[1].lower() for ln in gloss if ln.startswith("| **")]
  107. mine = [re.match(r"\| \*\*(.+?)\*\*", ln)[1].lower() for ln in gloss if ln.startswith("| **") and f"{NAME}.md" in ln]
  108. assert len(terms) > 100 and len(mine) >= 5, "the guard collected too little"
  109. # Older rows may repeat a term; this page's own terms must each appear exactly once.
  110. assert [t for t in mine if terms.count(t) != 1] == []
  111. def test_no_address_outside_the_documentation_ranges_and_no_em_dash_and_no_price_talk():
  112. body = text()
  113. assert "127.0.0.1" in body, "the guard collected nothing"
  114. assert not stray_addresses(body)
  115. assert "—" not in body
  116. assert not PRICE.findall(body), PRICE.findall(body)
  117. def test_the_address_and_price_guards_bite():
  118. assert stray_addresses("ping 10.0.0.7") == ["10.0.0.7"]
  119. assert not stray_addresses("ping 192.0.2.7 and 127.0.0.1")
  120. assert PRICE.findall("costs $12 per month")
  121. def test_only_the_sources_read_are_linked_and_no_public_instance_is_named():
  122. body = text()
  123. assert len(URL.findall(body)) >= 8, "the guard collected too few sources"
  124. assert not foreign_hosts(body), foreign_hosts(body)
  125. for needle in ("searx.space", "searx.be", "searx.tiekoetter", "priv.au"):
  126. assert needle not in body, needle
  127. def test_the_source_guard_bites():
  128. assert foreign_hosts("see https://searx.example.net/ and https://docs.searxng.org/x") == ["searx.example.net"]
  129. def test_every_cited_repository_path_exists():
  130. cited = sorted(set(PATH.findall(text())))
  131. assert len(cited) >= 6, "the guard collected too little"
  132. missing = [c for c in cited if not (ROOT / c.rstrip("/")).exists()]
  133. assert not missing, missing
  134. def test_every_claims_register_row_has_a_status():
  135. rows = register_rows(text())
  136. assert len(rows) >= 20, "the guard collected too few rows"
  137. assert not rows_missing_status(text())
  138. def test_the_register_guard_bites():
  139. bad = "## Claims register\n\n| Claim | Source | Status |\n|---|---|---|\n| X | y | maybe |\n"
  140. assert rows_missing_status(bad) == ["X"]
  141. def test_every_diagram_is_wrapped_has_alt_text_a_source_and_a_picture():
  142. body = text()
  143. assert len(DIAGRAM.findall(body)) == EXPECTED_DIAGRAMS
  144. assert not diagram_problems(body)
  145. def test_the_diagram_guard_bites():
  146. bare = "![too short](images/x.png)\n"
  147. assert diagram_problems(bare)
  148. long_alt = "![" + "a" * 151 + "](images/x.png)\n\n<details>\n<summary>Diagram source (Mermaid)</summary>\n\n```mermaid\nflowchart LR\n```\n\n</details>"
  149. assert any("alt text" in p for p in diagram_problems(long_alt))
  150. def test_the_lab_binds_to_loopback_and_never_to_every_address():
  151. code = "\n".join(b for t, b in FENCE.findall(text()) if t == "bash")
  152. assert "SEARXNG_BIND=127.0.0.1" in code and "ss -ltn" in code, "the guard collected nothing"
  153. assert not wildcard_binds(code), wildcard_binds(code)
  154. def test_the_lab_guard_bites():
  155. assert wildcard_binds("docker run -p 8080:8080 x")
  156. assert wildcard_binds("SEARXNG_BIND=0.0.0.0")
  157. assert wildcard_binds("SEARXNG_BIND=\n")
  158. assert not wildcard_binds("export SEARXNG_BIND=127.0.0.1")
  159. def test_memory_is_stated_as_unknown_and_no_invented_figure_is_given():
  160. body = text()
  161. assert "unknown" in body.lower()
  162. section = body.split("## Does it fit")[1].split("\n## ")[0]
  163. assert "unknown" in section.lower()
  164. assert "not measured" in section.lower() or "nothing was measured" in section.lower()
  165. assert not re.search(r"\b\d+\s?(?:MB|MiB|GB|GiB)\b", section.replace("1.2 to 1.6 GB", "").replace("2 GB", "")), section
  166. def test_the_image_digests_match_the_compose_file():
  167. compose = (ROOT / "workloads" / "searxng" / "docker-compose.yml").read_text(encoding="utf-8")
  168. digests = set(re.findall(r"sha256:[0-9a-f]{64}", compose))
  169. assert len(digests) == 2
  170. body = text()
  171. for d in digests:
  172. assert d in body, d
  173. def test_the_page_makes_no_statement_about_this_repositorys_own_posture():
  174. body = text().lower()
  175. for needle in ("this repository has no public", "this project has no public", "our firewall", "this repository is secure"):
  176. assert needle not in body, needle
  177. def test_the_checklist_covers_every_item_the_issue_asks_for():
  178. section = text().split("## The self-hosting checklist for any service")[1].split("\n## ")[0]
  179. rows = [ln for ln in section.splitlines() if ln.startswith("| ") and not ln.startswith("|---")][1:]
  180. assert len(rows) >= 9, "the guard collected too few rows"
  181. for word in ("Threat model", "Where it listens", "Who may reach it", "Secrets", "Updates", "Backups", "Monitoring", "Logging", "When not"):
  182. assert any(r.split("|")[1].strip().startswith(word) for r in rows), word
  183. assert all(r.rstrip().endswith("|") and r.count("|") >= 4 for r in rows)