test_metadata_lock_script.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. """Hermetic tests for the metadata-lock script in the connector cloud-init.
  2. The script is extracted from modules/twingate-bootstrap/cloud-init.yaml.tftpl
  3. (undoing the template's `$$` escaping and the YAML block indentation) and run
  4. with a fake `nft` and a fake `id` first on PATH, inside a temporary directory.
  5. The real nft is never invoked for a change: the one optional syntax check runs
  6. `nft -c` (check only) in a throwaway user and network namespace and skips when
  7. that is not possible.
  8. """
  9. import re
  10. import shutil
  11. import stat
  12. import subprocess
  13. from pathlib import Path
  14. import pytest
  15. ROOT = Path(__file__).resolve().parent.parent
  16. TEMPLATE = ROOT / "modules/twingate-bootstrap/cloud-init.yaml.tftpl"
  17. SCRIPT_PATH = "/usr/local/sbin/cah-metadata-lock"
  18. BASH = shutil.which("bash")
  19. def _run(args, **kwargs):
  20. """subprocess.run that reports the exit code instead of raising."""
  21. return subprocess.run(args, check=False, **kwargs)
  22. def extract_script(template_text: str, path: str = SCRIPT_PATH) -> str:
  23. """The write_files content for `path`, as it lands on the machine."""
  24. lines = template_text.splitlines()
  25. start = next(
  26. (i for i, line in enumerate(lines) if line.strip() == f"- path: {path}"), None
  27. )
  28. assert start is not None, f"{path} is not written by the template"
  29. body: list[str] = []
  30. in_content = False
  31. for line in lines[start + 1 :]:
  32. if not in_content:
  33. if line.strip() == "content: |":
  34. in_content = True
  35. continue
  36. # The block scalar ends at the first line indented less than 6 spaces
  37. # that is not blank (the next " - path:" entry or a %{ directive).
  38. if line.strip() and not line.startswith(" "):
  39. break
  40. body.append(line[6:] if line.startswith(" ") else "")
  41. assert body, f"{path} has no content"
  42. text = "\n".join(body).rstrip("\n") + "\n"
  43. # tftpl: "$$" renders as "$"; "${...}" would be an interpolation.
  44. assert "${" not in text, "an unescaped template interpolation reached the script"
  45. return text.replace("$$", "$")
  46. def make_fakes(tmp: Path, agent_uid: str | None) -> tuple[Path, Path, Path]:
  47. bindir = tmp / "bin"
  48. bindir.mkdir()
  49. calls = tmp / "calls.log"
  50. stdin_copy = tmp / "nft.stdin"
  51. reader = (
  52. 'while IFS= read -r line || [ -n "$line" ]; do '
  53. f'printf \'%s\\n\' "$line"; done > "{stdin_copy}"\n'
  54. )
  55. (bindir / "nft").write_text(
  56. f"#!{BASH}\n"
  57. f'echo "nft $*" >> "{calls}"\n'
  58. # Only shell builtins: PATH holds nothing but these fakes.
  59. + reader
  60. )
  61. if agent_uid is None:
  62. id_body = f'echo "id $*" >> "{calls}"\nexit 1\n'
  63. else:
  64. id_body = (
  65. f'echo "id $*" >> "{calls}"\n'
  66. f'if [ "$*" = "-u do-agent" ]; then echo {agent_uid}; exit 0; fi\n'
  67. "exit 1\n"
  68. )
  69. (bindir / "id").write_text(f"#!{BASH}\n{id_body}")
  70. for f in bindir.iterdir():
  71. f.chmod(f.stat().st_mode | stat.S_IXUSR)
  72. return bindir, calls, stdin_copy
  73. def run_script(tmp: Path, agent_uid: str | None):
  74. script = tmp / "cah-metadata-lock"
  75. script.write_text(extract_script(TEMPLATE.read_text(encoding="utf-8")))
  76. bindir, calls, stdin_copy = make_fakes(tmp, agent_uid)
  77. env = {"PATH": str(bindir), "HOME": str(tmp)}
  78. proc = _run(
  79. [BASH, str(script)], env=env, capture_output=True, text=True, timeout=30
  80. )
  81. call_lines = calls.read_text().splitlines() if calls.exists() else []
  82. ruleset = stdin_copy.read_text() if stdin_copy.exists() else ""
  83. return proc, call_lines, ruleset
  84. pytestmark = pytest.mark.skipif(BASH is None, reason="bash is not available")
  85. def test_extraction_finds_a_real_script():
  86. text = extract_script(TEMPLATE.read_text(encoding="utf-8"))
  87. assert text.startswith("#!/usr/bin/env bash\n")
  88. assert "set -euo pipefail" in text
  89. assert "169.254.169.254" in text
  90. def test_extraction_negative_case_missing_path_is_an_error():
  91. with pytest.raises(AssertionError):
  92. extract_script(TEMPLATE.read_text(encoding="utf-8"), "/usr/local/sbin/nope")
  93. def test_extraction_negative_case_rejects_an_interpolation():
  94. fake = " - path: /x\n content: |\n echo ${oops}\n"
  95. with pytest.raises(AssertionError):
  96. extract_script(fake, "/x")
  97. def test_do_agent_present_is_allowed_next_to_root(tmp_path):
  98. proc, _calls, ruleset = run_script(tmp_path, "998")
  99. assert proc.returncode == 0, proc.stderr
  100. assert "meta skuid != { 0, 998 }" in ruleset
  101. assert "uids: 0, 998" in proc.stdout
  102. def test_do_agent_missing_leaves_only_root_and_exits_zero(tmp_path):
  103. proc, _calls, ruleset = run_script(tmp_path, None)
  104. assert proc.returncode == 0, proc.stderr
  105. assert "meta skuid != { 0 }" in ruleset
  106. assert "," not in re.search(r"skuid != \{([^}]*)\}", ruleset).group(1)
  107. def test_ruleset_is_idempotent_and_self_contained(tmp_path):
  108. _proc, _calls, ruleset = run_script(tmp_path, "998")
  109. lines = [line.strip() for line in ruleset.splitlines()]
  110. first = lines.index("table inet cah_metadata")
  111. delete = lines.index("delete table inet cah_metadata")
  112. full = next(i for i, line in enumerate(lines) if line == "table inet cah_metadata {")
  113. assert first < delete < full
  114. assert "ip daddr 169.254.169.254 meta skuid != { 0, 998 } reject with icmp type admin-prohibited" in lines
  115. assert "type filter hook output priority 0; policy accept;" in lines
  116. # No flush of the whole ruleset: other rules are never touched.
  117. assert "flush ruleset" not in ruleset
  118. def test_only_the_fake_nft_and_id_are_invoked(tmp_path):
  119. proc, calls, _ruleset = run_script(tmp_path, "998")
  120. assert proc.returncode == 0, proc.stderr
  121. assert calls == ["id -u do-agent", "nft -f -"]
  122. def test_a_failing_nft_fails_the_script(tmp_path):
  123. script = tmp_path / "s"
  124. script.write_text(extract_script(TEMPLATE.read_text(encoding="utf-8")))
  125. bindir = tmp_path / "bin"
  126. bindir.mkdir()
  127. (bindir / "nft").write_text(f"#!{BASH}\nexit 1\n")
  128. (bindir / "id").write_text(f"#!{BASH}\nexit 1\n")
  129. for f in bindir.iterdir():
  130. f.chmod(f.stat().st_mode | stat.S_IXUSR)
  131. proc = _run(
  132. [BASH, str(script)],
  133. env={"PATH": str(bindir)},
  134. capture_output=True,
  135. text=True,
  136. timeout=30,
  137. )
  138. assert proc.returncode != 0
  139. def _can_check_syntax() -> bool:
  140. nft, unshare = shutil.which("nft"), shutil.which("unshare")
  141. if not nft or not unshare:
  142. return False
  143. probe = _run(
  144. [unshare, "-rn", nft, "-c", "-f", "-"],
  145. input="table inet cah_probe\n",
  146. capture_output=True,
  147. text=True,
  148. timeout=30,
  149. )
  150. return probe.returncode == 0
  151. @pytest.mark.skipif(not _can_check_syntax(), reason="unshare -rn nft -c is unavailable here")
  152. def test_generated_ruleset_passes_nft_syntax_check(tmp_path):
  153. _proc, _calls, ruleset = run_script(tmp_path, "998")
  154. check = _run(
  155. [shutil.which("unshare"), "-rn", shutil.which("nft"), "-c", "-f", "-"],
  156. input=ruleset,
  157. capture_output=True,
  158. text=True,
  159. timeout=30,
  160. )
  161. assert check.returncode == 0, check.stderr
  162. # Negative case: the checker really rejects a broken ruleset.
  163. bad = _run(
  164. [shutil.which("unshare"), "-rn", shutil.which("nft"), "-c", "-f", "-"],
  165. input=ruleset.replace("skuid", "skuidd"),
  166. capture_output=True,
  167. text=True,
  168. timeout=30,
  169. )
  170. assert bad.returncode != 0
  171. def test_template_gates_the_lock_on_metadata_lock():
  172. text = TEMPLATE.read_text(encoding="utf-8")
  173. # The nftables package entry is shared with host_firewall (issue #90), so it
  174. # is gated on "metadata_lock || host_firewall"; the script/unit block and the
  175. # runcmd block are gated on metadata_lock alone.
  176. assert len(re.findall(r"%\{ if metadata_lock ~\}", text)) == 2
  177. assert len(re.findall(r"%\{ if metadata_lock \|\| host_firewall ~\}", text)) == 1
  178. # Two more endifs close the host_firewall blocks (script/unit and runcmd).
  179. # Five more close the node_exporter blocks (package, files, runcmd, and the
  180. # two lines inside the host firewall script). Three more close the
  181. # log_shipping blocks (package, files, runcmd).
  182. assert len(re.findall(r"%\{ endif ~\}", text)) == 13
  183. assert len(re.findall(r"%\{ if node_exporter ~\}", text)) == 5
  184. assert len(re.findall(r"%\{ if log_shipping ~\}", text)) == 3