test_secret_rule.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. """The one placeholder rule for required secrets, and everywhere it is used.
  2. scripts/secret_rule.py is the single definition. The shell scripts call it, the
  3. Spacelift hook script carries a case-statement copy that these tests pin to it,
  4. and the OpenTofu validations carry its RE2 pattern, pinned here by text.
  5. """
  6. import importlib.util
  7. import os
  8. import re
  9. import shutil
  10. import stat
  11. import subprocess
  12. import sys
  13. from pathlib import Path
  14. import pytest
  15. ROOT = Path(__file__).resolve().parent.parent
  16. SCRIPT = ROOT / "scripts" / "secret_rule.py"
  17. DOPPLER_ENV = ROOT / "scripts" / "spacelift" / "doppler-env.sh"
  18. DEMO = ROOT / "scripts" / "demo_monitoring.sh"
  19. WP_LAB = ROOT / "labs" / "wordpress-at-scale"
  20. spec = importlib.util.spec_from_file_location("secret_rule", SCRIPT)
  21. sr = importlib.util.module_from_spec(spec)
  22. sys.modules["secret_rule"] = sr
  23. spec.loader.exec_module(sr)
  24. # Real-looking values are assembled at import time so no token-shaped literal sits
  25. # in the source for a secret scanner to flag. The pieces are short on purpose.
  26. REAL_SECRET = "k3Jf9Qw2" + "Zr8LmN4p" + "Xs7Tv1Ye"
  27. HEX_SECRET = "3f9a1c07" + "be52d648" + "1a0c7e93" + "d5b2f814"
  28. DOPPLER_TOKEN = ".".join(["dp", "st", "cah-ctx", "Zm9vYmFy" + "YmF6cXV4"])
  29. DOPPLER_SITE_TOKEN = ".".join(["dp", "st", "cah-site-hostboot", "Zm9vYmFy" + "YmF6cXV4"])
  30. PLACEHOLDERS = [
  31. "",
  32. " ",
  33. "your_token",
  34. "YOUR_TOKEN_HERE",
  35. "Your-Password",
  36. "changeme",
  37. "ChangeMe123",
  38. "change-me-please",
  39. "replace-with-your-token",
  40. "REPLACE_WITH_VALUE",
  41. "<token>",
  42. "<paste the token here>",
  43. "example",
  44. "my-example-secret-value",
  45. "placeholder",
  46. "A-PLACEHOLDER-value",
  47. "xxx",
  48. "xxxxxxxxxxxxxxxx",
  49. "dp.st.your-config.abcdefgh",
  50. "todo",
  51. "admin",
  52. "Password",
  53. "secret",
  54. "test",
  55. ]
  56. REAL_LOOKING = [
  57. REAL_SECRET,
  58. HEX_SECRET,
  59. DOPPLER_SITE_TOKEN,
  60. "fixture-bootstrap-token-0001",
  61. "correct-horse-battery-staple-9",
  62. ]
  63. @pytest.mark.parametrize("value", PLACEHOLDERS)
  64. def test_placeholders_and_empty_are_rejected(value):
  65. assert sr.is_placeholder(value)
  66. with pytest.raises(sr.SecretError):
  67. sr.require_secret("SOME_TOKEN", value)
  68. def test_unset_is_rejected():
  69. assert sr.is_placeholder(None)
  70. with pytest.raises(sr.SecretError):
  71. sr.require_secret("SOME_TOKEN", None)
  72. @pytest.mark.parametrize("value", REAL_LOOKING)
  73. def test_real_looking_values_are_accepted(value):
  74. assert not sr.is_placeholder(value)
  75. assert sr.require_secret("SOME_TOKEN", value) == value
  76. def message_for(value):
  77. with pytest.raises(sr.SecretError) as err:
  78. sr.require_secret("SOME_TOKEN", value)
  79. return str(err.value)
  80. @pytest.mark.parametrize("value", [v for v in PLACEHOLDERS if v.strip()])
  81. def test_the_value_never_appears_in_the_error(value):
  82. # The message is the same whatever the value is, so it cannot carry it.
  83. assert "SOME_TOKEN" in message_for(value)
  84. assert message_for(value) == message_for("")
  85. def run_cli(name, value):
  86. env = {k: v for k, v in os.environ.items() if k != name}
  87. return subprocess.run(
  88. [sys.executable, "-I", str(SCRIPT), name],
  89. input=value, env=env, capture_output=True, text=True, check=False,
  90. )
  91. @pytest.mark.parametrize("value", ["", "changeme-now-please", "your_password_here"])
  92. def test_cli_rejects_and_names_the_variable_without_the_value(value):
  93. out = run_cli("GRAFANA_ADMIN_PASSWORD", value)
  94. assert out.returncode == 1
  95. assert "GRAFANA_ADMIN_PASSWORD" in out.stderr
  96. if value:
  97. assert value not in out.stderr and value not in out.stdout
  98. def test_cli_accepts_a_real_value_and_prints_nothing():
  99. value = REAL_SECRET
  100. out = run_cli("GRAFANA_ADMIN_PASSWORD", value)
  101. assert out.returncode == 0
  102. assert value not in out.stdout + out.stderr
  103. def test_cli_guard_bites_on_a_missing_name():
  104. out = subprocess.run([sys.executable, "-I", str(SCRIPT)], input="x", capture_output=True, text=True, check=False)
  105. assert out.returncode == 2
  106. # --- The OpenTofu validations carry the same pattern, byte for byte. ---
  107. TOKEN_VARIABLES = [
  108. ROOT / "stacks" / "10-access" / "variables.tf",
  109. ROOT / "modules" / "twingate-connector" / "variables.tf",
  110. ROOT / "modules" / "twingate-bootstrap" / "variables.tf",
  111. ]
  112. def token_block(path):
  113. text = path.read_text()
  114. start = text.index('variable "log_shipping_bootstrap_token"')
  115. return text[start : text.index("\nvariable ", start + 1)] if "\nvariable " in text[start + 1 :] else text[start:]
  116. @pytest.mark.parametrize("path", [p for p in TOKEN_VARIABLES if "stacks" in str(p) or "twingate-bootstrap" in str(p)])
  117. def test_tofu_token_validation_uses_the_one_pattern(path):
  118. block = token_block(path)
  119. assert sr.PLACEHOLDER_RE2 in block, f"{path.relative_to(ROOT)} must carry the pattern from scripts/secret_rule.py"
  120. def test_the_pattern_is_re2_safe_and_matches_the_python_rule():
  121. assert '"' not in sr.PLACEHOLDER_RE2 and "\\" not in sr.PLACEHOLDER_RE2
  122. for v in PLACEHOLDERS:
  123. if v.strip():
  124. assert re.search(sr.PLACEHOLDER_RE2, v), v
  125. for v in REAL_LOOKING:
  126. assert not re.search(sr.PLACEHOLDER_RE2, v), v
  127. # --- The Spacelift hook script uses a shell copy, pinned to the Python rule. ---
  128. def shell_is_placeholder(value):
  129. cmd = f'. "{DOPPLER_ENV}"; cah_doppler_is_placeholder "$V" && echo placeholder || echo ok'
  130. out = subprocess.run(["/bin/sh", "-c", cmd], env={"PATH": os.environ["PATH"], "V": value},
  131. capture_output=True, text=True, check=True)
  132. return out.stdout.strip() == "placeholder"
  133. @pytest.mark.parametrize("value", PLACEHOLDERS + REAL_LOOKING)
  134. def test_shell_copy_agrees_with_the_python_rule(value):
  135. assert shell_is_placeholder(value) == sr.is_placeholder(value), repr(value)
  136. TOOLS = ["uname", "sed", "mkdir", "rm", "sha256sum", "tar", "cat", "env", "printf", "mktemp", "tr"]
  137. def hook(tmp_path, name, value, doppler_token=DOPPLER_TOKEN):
  138. bin_dir = tmp_path / "bin"
  139. bin_dir.mkdir(exist_ok=True)
  140. for tool in TOOLS:
  141. found = shutil.which(tool)
  142. if found and not (bin_dir / tool).exists():
  143. (bin_dir / tool).symlink_to(found)
  144. stub = bin_dir / "doppler"
  145. stub.write_text(
  146. '#!/bin/sh\nif [ "$1" = "--version" ]; then echo v3.77.0; exit 0; fi\nprintf \'%s\' "$STUB_VALUE"\n'
  147. )
  148. stub.chmod(stub.stat().st_mode | stat.S_IXUSR)
  149. env = {
  150. "PATH": str(bin_dir), "CAH_DOPPLER_DIR": str(tmp_path / "dl"),
  151. "DOPPLER_TOKEN": doppler_token, "DOPPLER_PROJECT": "proj", "DOPPLER_CONFIG": "prd",
  152. "TF_VAR_spacelift_run_type": "TRACKED", "TF_VAR_spacelift_commit_branch": "main",
  153. "STUB_VALUE": value,
  154. }
  155. cmd = f'. "{DOPPLER_ENV}"; cah_doppler_env {name}; echo "rc=$?"; echo "GOT=${{{name}:-unset}}"'
  156. return subprocess.run(["/bin/sh", "-c", cmd], env=env, capture_output=True, text=True, check=False)
  157. @pytest.mark.parametrize("value", ["changeme-changeme", "your_token_value", "<token>", "xxxxxxxx"])
  158. def test_hook_refuses_a_placeholder_secret_and_never_prints_it(tmp_path, value):
  159. out = hook(tmp_path, "TWINGATE_API_TOKEN", value)
  160. assert "rc=1" in out.stdout and "GOT=unset" in out.stdout
  161. assert "TWINGATE_API_TOKEN" in out.stdout
  162. assert value not in out.stdout + out.stderr
  163. def test_hook_accepts_a_real_looking_secret(tmp_path):
  164. out = hook(tmp_path, "TWINGATE_API_TOKEN", REAL_SECRET)
  165. assert "rc=0" in out.stdout and f"GOT={REAL_SECRET}" in out.stdout
  166. def test_hook_does_not_apply_the_rule_to_a_public_value(tmp_path):
  167. # A public SSH key may carry a comment such as example.com; it is not a secret.
  168. key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIexample user@example.com"
  169. out = hook(tmp_path, "ADMIN_SSH_PUBLIC_KEY", key)
  170. assert "rc=0" in out.stdout
  171. def test_hook_refuses_a_placeholder_doppler_token(tmp_path):
  172. out = hook(tmp_path, "TWINGATE_API_TOKEN", REAL_SECRET, doppler_token="dp.st.your-token")
  173. assert "rc=1" in out.stdout
  174. assert "DOPPLER_TOKEN" in out.stdout
  175. assert "dp.st.your-token" not in out.stdout + out.stderr
  176. # --- scripts/demo_monitoring.sh: the Grafana admin password ---
  177. def demo_env(tmp_path, shell_value=None, env_file=None):
  178. lab = tmp_path / "lab"
  179. lab.mkdir(exist_ok=True)
  180. shutil.copy(ROOT / "labs" / "demo-monitoring" / "env.example", lab / "env.example")
  181. if env_file is not None:
  182. (lab / ".env").write_text(env_file)
  183. env = {k: v for k, v in os.environ.items() if k != "GRAFANA_ADMIN_PASSWORD"}
  184. if shell_value is not None:
  185. env["GRAFANA_ADMIN_PASSWORD"] = shell_value
  186. out = subprocess.run(
  187. ["bash", "-c", f'source "{DEMO}"; LAB="{lab}"; ensure_env'],
  188. env=env, capture_output=True, text=True, check=False,
  189. )
  190. return lab, out
  191. @pytest.mark.parametrize("value", ["changeme", "your_password_here", "admin", "<password>"])
  192. def test_demo_refuses_a_placeholder_from_the_shell(tmp_path, value):
  193. _, out = demo_env(tmp_path, shell_value=value)
  194. assert out.returncode != 0
  195. assert "GRAFANA_ADMIN_PASSWORD" in out.stderr
  196. assert value not in out.stdout + out.stderr
  197. @pytest.mark.parametrize("value", ["changeme", "your_password_here", "password"])
  198. def test_demo_refuses_a_placeholder_in_the_env_file_and_leaves_the_file_alone(tmp_path, value):
  199. body = f"GRAFANA_ADMIN_PASSWORD={value}\nDEMO_GRAFANA_PORT=3999\n"
  200. lab, out = demo_env(tmp_path, env_file=body)
  201. assert out.returncode != 0
  202. assert "GRAFANA_ADMIN_PASSWORD" in out.stderr
  203. assert value not in out.stdout + out.stderr
  204. assert (lab / ".env").read_text() == body
  205. def test_demo_accepts_a_real_password_and_does_not_rewrite_the_file(tmp_path):
  206. body = f"GRAFANA_ADMIN_PASSWORD={REAL_SECRET}\n"
  207. lab, out = demo_env(tmp_path, env_file=body)
  208. assert out.returncode == 0
  209. assert (lab / ".env").read_text() == body
  210. def test_demo_generates_a_password_for_an_empty_value_and_keeps_other_settings(tmp_path):
  211. lab, out = demo_env(tmp_path, env_file="GRAFANA_ADMIN_PASSWORD=\nDEMO_GRAFANA_PORT=3999\n")
  212. assert out.returncode == 0
  213. text = (lab / ".env").read_text()
  214. assert "DEMO_GRAFANA_PORT=3999" in text, "an existing .env must not be overwritten"
  215. value = re.search(r"^GRAFANA_ADMIN_PASSWORD=(.+)$", text, re.MULTILINE).group(1)
  216. assert len(value) >= 20 and not sr.is_placeholder(value)
  217. assert value not in out.stdout + out.stderr
  218. def test_demo_generates_a_file_when_there_is_none(tmp_path):
  219. lab, out = demo_env(tmp_path)
  220. assert out.returncode == 0
  221. value = re.search(r"^GRAFANA_ADMIN_PASSWORD=(.+)$", (lab / ".env").read_text(), re.MULTILINE).group(1)
  222. assert len(value) >= 20 and value not in out.stdout + out.stderr
  223. def test_demo_env_example_carries_no_value_and_says_required():
  224. text = (ROOT / "labs" / "demo-monitoring" / "env.example").read_text()
  225. assert re.search(r"^GRAFANA_ADMIN_PASSWORD=$", text, re.MULTILINE)
  226. assert "required" in text.lower()
  227. # --- labs/wordpress-at-scale/lab.sh: the origin secret ---
  228. def wp_check(tmp_path, env_file):
  229. lab = tmp_path / "wp"
  230. lab.mkdir(exist_ok=True)
  231. if env_file is not None:
  232. (lab / ".env").write_text(env_file)
  233. env = {k: v for k, v in os.environ.items() if k != "ORIGIN_SECRET"}
  234. out = subprocess.run(
  235. ["bash", "-c", f'source "{WP_LAB / "lab.sh"}"; LAB="{lab}"; ensure_origin_secret'],
  236. env=env, capture_output=True, text=True, check=False,
  237. )
  238. return lab, out
  239. @pytest.mark.parametrize("value", ["changeme", "your_secret_here", "example"])
  240. def test_wp_lab_refuses_a_placeholder_origin_secret(tmp_path, value):
  241. _lab, out = wp_check(tmp_path, f"ORIGIN_SECRET={value}\n")
  242. assert out.returncode != 0
  243. assert "ORIGIN_SECRET" in out.stderr
  244. assert value not in out.stdout + out.stderr
  245. def test_wp_lab_generates_for_missing_or_empty_and_accepts_a_real_one(tmp_path):
  246. for body in (None, "ORIGIN_SECRET=\n"):
  247. lab, out = wp_check(tmp_path, body)
  248. assert out.returncode == 0, out.stderr
  249. value = re.search(r"^ORIGIN_SECRET=(.+)$", (lab / ".env").read_text(), re.MULTILINE).group(1)
  250. assert re.fullmatch(r"[0-9a-f]{32}", value) and value not in out.stdout + out.stderr
  251. real = HEX_SECRET
  252. lab, out = wp_check(tmp_path, f"ORIGIN_SECRET={real}\n")
  253. assert out.returncode == 0
  254. assert (lab / ".env").read_text() == f"ORIGIN_SECRET={real}\n"
  255. def test_wp_lab_powershell_twin_carries_the_one_pattern():
  256. text = (WP_LAB / "lab.ps1").read_text()
  257. assert sr.PLACEHOLDER_RE2 in text
  258. assert "refusing to start: ORIGIN_SECRET" in text
  259. def test_wp_lab_bash_refuses_before_compose_runs():
  260. text = (WP_LAB / "lab.sh").read_text()
  261. up = text.split(" up)")[1].split("compose --env-file")[0]
  262. assert "ensure_origin_secret" in up