test_doppler_env.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. """Tests for scripts/spacelift/doppler-env.sh.
  2. The script is sourced by Spacelift hooks under busybox ash, so it runs here
  3. under plain /bin/sh. `doppler` and `curl` are stubs, and PATH holds only
  4. symlinks to the few tools the script uses, so the real Doppler CLI on the
  5. developer machine can never be picked up.
  6. """
  7. import re
  8. import shutil
  9. import stat
  10. import subprocess
  11. from pathlib import Path
  12. import pytest
  13. SCRIPT = (
  14. Path(__file__).resolve().parent.parent / "scripts" / "spacelift" / "doppler-env.sh"
  15. )
  16. TOOLS = ["uname", "sed", "mkdir", "rm", "sha256sum", "tar", "cat", "env", "printf", "mktemp"]
  17. SECRET = "dp_test_SECRET_VALUE_123"
  18. DOPPLER_STUB = """#!/bin/sh
  19. # Stub: `doppler --version` and `doppler secrets get NAME --plain ...`.
  20. if [ "$1" = "--version" ]; then echo "v3.77.0"; exit 0; fi
  21. if [ "$1" = "secrets" ] && [ "$2" = "get" ]; then
  22. [ -n "$STUB_FAIL" ] && exit 1
  23. eval "printf '%s' \\"\\${STUB_$3:-}\\""
  24. exit 0
  25. fi
  26. exit 2
  27. """
  28. CURL_STUB = """#!/bin/sh
  29. # Stub: writes a bogus archive to the -o target, so the checksum must fail.
  30. while [ "$#" -gt 0 ]; do
  31. if [ "$1" = "-o" ]; then printf 'not a real archive' > "$2"; fi
  32. shift
  33. done
  34. exit 0
  35. """
  36. def _write_exec(path: Path, body: str) -> None:
  37. path.write_text(body)
  38. path.chmod(path.stat().st_mode | stat.S_IXUSR)
  39. @pytest.fixture()
  40. def sandbox(tmp_path):
  41. """A PATH directory with only the tools the script needs."""
  42. bin_dir = tmp_path / "bin"
  43. bin_dir.mkdir()
  44. for tool in TOOLS:
  45. found = shutil.which(tool)
  46. if found:
  47. (bin_dir / tool).symlink_to(found)
  48. return tmp_path, bin_dir
  49. def run(sandbox, args, env_extra=None, with_doppler=True):
  50. tmp_path, bin_dir = sandbox
  51. if with_doppler:
  52. _write_exec(bin_dir / "doppler", DOPPLER_STUB)
  53. else:
  54. _write_exec(bin_dir / "curl", CURL_STUB)
  55. env = {
  56. "PATH": str(bin_dir),
  57. "CAH_DOPPLER_DIR": str(tmp_path / "dl"),
  58. "DOPPLER_TOKEN": "dp.st.test",
  59. "DOPPLER_PROJECT": "proj",
  60. "DOPPLER_CONFIG": "prd",
  61. "TF_VAR_spacelift_run_type": "TRACKED",
  62. "TF_VAR_spacelift_commit_branch": "main",
  63. "STUB_DIGITALOCEAN_TOKEN": SECRET,
  64. }
  65. env.update(env_extra or {})
  66. # Source the script, then print what a following phase would see.
  67. cmd = f'. "{SCRIPT}"; cah_doppler_env {args}; rc=$?; echo "rc=$rc"; echo "TOKEN=${{DIGITALOCEAN_TOKEN:-unset}}"'
  68. return subprocess.run(
  69. ["/bin/sh", "-c", cmd], env=env, capture_output=True, text=True, check=False
  70. )
  71. def test_tracked_main_exports_and_masks(sandbox):
  72. out = run(sandbox, "DIGITALOCEAN_TOKEN").stdout
  73. assert "rc=0" in out
  74. assert f"TOKEN={SECRET}" in out
  75. assert f"::add-mask {SECRET}" in out
  76. assert "loaded DIGITALOCEAN_TOKEN" in out
  77. def test_value_only_appears_in_mask_line_and_phase_env(sandbox):
  78. out = run(sandbox, "DIGITALOCEAN_TOKEN").stdout
  79. # The log line that announces the load must not carry the value.
  80. log_lines = [ln for ln in out.splitlines() if ln.startswith("doppler-env:")]
  81. assert log_lines and all(SECRET not in ln for ln in log_lines)
  82. @pytest.mark.parametrize("run_type", ["PROPOSED", "TASK", "TESTING", "PARSE", ""])
  83. def test_other_run_types_get_nothing(sandbox, run_type):
  84. result = run(sandbox, "DIGITALOCEAN_TOKEN", {"TF_VAR_spacelift_run_type": run_type})
  85. assert "rc=0" in result.stdout
  86. assert "TOKEN=unset" in result.stdout
  87. assert SECRET not in result.stdout
  88. assert "skipping" in result.stdout
  89. def test_destroy_run_on_main_is_allowed(sandbox):
  90. result = run(
  91. sandbox, "DIGITALOCEAN_TOKEN", {"TF_VAR_spacelift_run_type": "DESTROY"}
  92. )
  93. assert f"TOKEN={SECRET}" in result.stdout
  94. @pytest.mark.parametrize("branch", ["feature/x", "mainline", ""])
  95. def test_non_main_branch_gets_nothing(sandbox, branch):
  96. result = run(
  97. sandbox, "DIGITALOCEAN_TOKEN", {"TF_VAR_spacelift_commit_branch": branch}
  98. )
  99. assert "rc=0" in result.stdout
  100. assert "TOKEN=unset" in result.stdout
  101. assert SECRET not in result.stdout
  102. @pytest.mark.parametrize(
  103. "missing", ["DOPPLER_TOKEN", "DOPPLER_PROJECT", "DOPPLER_CONFIG"]
  104. )
  105. def test_missing_doppler_setting_fails(sandbox, missing):
  106. result = run(sandbox, "DIGITALOCEAN_TOKEN", {missing: ""})
  107. assert "rc=1" in result.stdout
  108. assert f"{missing} is not set" in result.stdout
  109. assert "TOKEN=unset" in result.stdout
  110. def test_no_names_fails(sandbox):
  111. result = run(sandbox, "")
  112. assert "rc=1" in result.stdout
  113. assert "no secret names" in result.stdout
  114. @pytest.mark.parametrize("bad", ["1ABC", "A-B", "A;B", "=B", "A=", "A=B=C", "$(id)"])
  115. def test_invalid_name_fails_before_anything_runs(sandbox, bad):
  116. result = run(sandbox, f"'{bad}'")
  117. assert "rc=1" in result.stdout
  118. assert "invalid secret name" in result.stdout
  119. assert "TOKEN=unset" in result.stdout
  120. def test_doppler_failure_fails_closed(sandbox):
  121. result = run(sandbox, "DIGITALOCEAN_TOKEN", {"STUB_FAIL": "1"})
  122. assert "rc=1" in result.stdout
  123. assert "could not read DIGITALOCEAN_TOKEN" in result.stdout
  124. assert "TOKEN=unset" in result.stdout
  125. def test_empty_secret_fails_closed(sandbox):
  126. result = run(sandbox, "DIGITALOCEAN_TOKEN", {"STUB_DIGITALOCEAN_TOKEN": ""})
  127. assert "rc=1" in result.stdout
  128. assert "is empty in Doppler" in result.stdout
  129. def test_multiple_names_all_loaded(sandbox):
  130. result = run(
  131. sandbox,
  132. "DIGITALOCEAN_TOKEN TWINGATE_API_TOKEN",
  133. {"STUB_TWINGATE_API_TOKEN": "tw_secret_456"},
  134. )
  135. assert "rc=0" in result.stdout
  136. assert "::add-mask tw_secret_456" in result.stdout
  137. def test_var_equals_name_maps_doppler_name_to_env_var(sandbox):
  138. result = run(
  139. sandbox,
  140. "TF_VAR_admin_user_ids=ADMIN_USER_IDS",
  141. {"STUB_ADMIN_USER_IDS": '["abc"]'},
  142. )
  143. out = result.stdout
  144. assert "rc=0" in out
  145. assert "loaded ADMIN_USER_IDS as TF_VAR_admin_user_ids" in out
  146. assert '::add-mask ["abc"]' in out
  147. def test_mapped_var_is_what_the_phase_sees(sandbox):
  148. _, bin_dir = sandbox
  149. _write_exec(bin_dir / "doppler", DOPPLER_STUB)
  150. env = {
  151. "PATH": str(bin_dir),
  152. "DOPPLER_TOKEN": "t",
  153. "DOPPLER_PROJECT": "p",
  154. "DOPPLER_CONFIG": "prd",
  155. "TF_VAR_spacelift_run_type": "TRACKED",
  156. "TF_VAR_spacelift_commit_branch": "main",
  157. "STUB_ADMIN_USER_IDS": '["abc"]',
  158. }
  159. cmd = f'. "{SCRIPT}"; cah_doppler_env TF_VAR_admin_user_ids=ADMIN_USER_IDS; env'
  160. result = subprocess.run(
  161. ["/bin/sh", "-c", cmd], env=env, capture_output=True, text=True, check=False
  162. )
  163. out = result.stdout
  164. assert 'TF_VAR_admin_user_ids=["abc"]' in out
  165. assert "\nADMIN_USER_IDS=" not in out
  166. def test_bad_checksum_refuses_to_run_downloaded_cli(sandbox):
  167. result = run(sandbox, "DIGITALOCEAN_TOKEN", with_doppler=False)
  168. assert "rc=1" in result.stdout
  169. assert "checksum mismatch" in result.stdout
  170. assert "TOKEN=unset" in result.stdout
  171. tmp_path, _ = sandbox
  172. assert not any((tmp_path / "dl").glob("*.tar.gz"))
  173. def test_download_folder_is_never_a_fixed_shared_name():
  174. text = SCRIPT.read_text()
  175. assert "/tmp/cah-doppler" not in text
  176. assert "mktemp -d" in text
  177. def test_unset_download_folder_is_a_new_private_folder(sandbox):
  178. tmp_path, _ = sandbox
  179. scratch = tmp_path / "scratch"
  180. scratch.mkdir()
  181. result = run(
  182. sandbox,
  183. "DIGITALOCEAN_TOKEN",
  184. env_extra={"CAH_DOPPLER_DIR": "", "TMPDIR": str(scratch)},
  185. with_doppler=False,
  186. )
  187. assert "checksum mismatch" in result.stdout # it got as far as the download, into the new folder
  188. made = list(scratch.iterdir())
  189. assert len(made) == 1 and made[0].is_dir()
  190. assert stat.S_IMODE(made[0].stat().st_mode) == 0o700
  191. def test_a_symlinked_download_folder_is_refused(sandbox):
  192. tmp_path, _ = sandbox
  193. elsewhere = tmp_path / "elsewhere"
  194. elsewhere.mkdir()
  195. (tmp_path / "link").symlink_to(elsewhere)
  196. result = run(sandbox, "DIGITALOCEAN_TOKEN", env_extra={"CAH_DOPPLER_DIR": str(tmp_path / "link")}, with_doppler=False)
  197. assert "refusing" in result.stdout and "rc=1" in result.stdout
  198. assert list(elsewhere.iterdir()) == []
  199. def test_script_has_no_trace_or_unsafe_echo():
  200. text = SCRIPT.read_text()
  201. assert "set -x" not in text
  202. assert not re.search(r"\|\s*(ba|da|a)?sh\b", text), (
  203. "never pipe a download into a shell"
  204. )
  205. CONFIG = Path(__file__).resolve().parent.parent / ".spacelift" / "config.yml"
  206. def _config_calls():
  207. """Map stack -> hook -> the cah_doppler_env argument line, without a YAML parser."""
  208. calls, stack, hook = {}, None, None
  209. for line in CONFIG.read_text().splitlines():
  210. if re.match(r"^ [a-z0-9-]+:\s*$", line):
  211. stack = line.strip().rstrip(":")
  212. calls[stack] = {}
  213. elif re.match(r"^ (before|after)_[a-z]+:\s*$", line):
  214. hook = line.strip().rstrip(":")
  215. elif "cah_doppler_env" in line and stack and hook:
  216. calls[stack][hook] = line.split("cah_doppler_env", 1)[1].split()
  217. return calls
  218. def test_config_loads_same_names_at_init_and_apply():
  219. calls = _config_calls()
  220. assert calls, "no stacks found in .spacelift/config.yml"
  221. for stack, hooks in calls.items():
  222. assert set(hooks) == {"before_init", "before_apply"}, stack
  223. assert hooks["before_init"] == hooks["before_apply"], stack
  224. def test_config_names_are_valid_and_carry_no_values():
  225. for stack, hooks in _config_calls().items():
  226. for names in hooks.values():
  227. assert names, stack
  228. for arg in names:
  229. var, _, src = arg.partition("=")
  230. for name in (var, src or var):
  231. assert re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name), (stack, arg)