test_secret_separation.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. """Per-cloud secret separation, repository side (phase 2c-iii of issue #22).
  2. Design section 4, point 4: each cloud gets its own Doppler config and Spacelift
  3. context, and a stack may only ask for its own cloud's secrets. Doppler cannot be
  4. called from CI, so these tests prove only what the repository declares: which
  5. secret NAMES each stack requests. They cannot prove that a Doppler token is
  6. narrow or that a context is attached to the right stacks. See "More than one
  7. cloud" in docs/spacelift-secrets.md.
  8. The config is parsed with PyYAML (a pinned CI test dependency) and validated
  9. fail-closed: any shape this file does not understand is a violation, never a
  10. silent skip.
  11. """
  12. import re
  13. from pathlib import Path
  14. import pytest
  15. import yaml
  16. ROOT = Path(__file__).resolve().parent.parent
  17. CONFIG = ROOT / ".spacelift" / "config.yml"
  18. SCRIPT = ROOT / "scripts" / "spacelift" / "doppler-env.sh"
  19. HOOKS = ("before_init", "before_apply")
  20. SOURCE_LINE = ". /mnt/workspace/source/scripts/spacelift/doppler-env.sh"
  21. NAME = r"[A-Za-z_][A-Za-z0-9_]*"
  22. CALL_RE = re.compile(rf"cah_doppler_env( {NAME}(={NAME})?)+")
  23. # Every accepted stack name matches exactly one of these. Anything else fails.
  24. STACK_PATTERNS = {
  25. "digitalocean": re.compile(r"cah-00-foundation|cah-10-access|cah-20-telemetry"),
  26. "aws": re.compile(r"cah-aws-[a-z0-9]+(-[a-z0-9]+)*"),
  27. "azure": re.compile(r"cah-azure-[a-z0-9]+(-[a-z0-9]+)*"),
  28. "gcp": re.compile(r"cah-gcp-[a-z0-9]+(-[a-z0-9]+)*"),
  29. }
  30. # Prefixes that identify a cloud's own credentials and settings.
  31. CLOUD_PREFIXES = {
  32. "digitalocean": ("DIGITALOCEAN_",),
  33. "aws": ("AWS_",),
  34. "azure": ("ARM_", "AZURE_"),
  35. "gcp": ("GOOGLE_", "GCP_"),
  36. }
  37. # Non-cloud names any stack may request: exact names, not prefixes, so a cloud
  38. # credential cannot hide behind an allowed prefix (ADMIN_AWS_SECRET_...).
  39. SHARED_NAMES = frozenset(
  40. {
  41. "TWINGATE_API_TOKEN",
  42. "TWINGATE_NETWORK",
  43. "ADMIN_SSH_PUBLIC_KEY",
  44. "ADMIN_SSH_KEY_NAME",
  45. "ADMIN_USER_IDS",
  46. }
  47. )
  48. def provider_for(stack):
  49. """The provider of a stack name, or None when it matches no pattern."""
  50. hits = [p for p, rx in STACK_PATTERNS.items() if rx.fullmatch(str(stack))]
  51. return hits[0] if len(hits) == 1 else None
  52. class _Strict(yaml.SafeLoader):
  53. """SafeLoader that rejects duplicate keys."""
  54. def _no_dupes(loader, node, deep=False):
  55. keys = [loader.construct_object(k, deep=True) for k, _ in node.value]
  56. if len(keys) != len(set(map(repr, keys))):
  57. raise yaml.constructor.ConstructorError(
  58. None, None, "duplicate key", node.start_mark
  59. )
  60. return yaml.SafeLoader.construct_mapping(loader, node, deep)
  61. _Strict.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _no_dupes)
  62. def load(text):
  63. """Parse the config. Returns (data, problems); aliases and anchors are refused."""
  64. try:
  65. for event in yaml.parse(text, Loader=yaml.SafeLoader):
  66. if isinstance(event, yaml.AliasEvent) or getattr(event, "anchor", None):
  67. return None, ["config: anchors and aliases are not allowed"]
  68. return yaml.load(text, Loader=_Strict), [] # _Strict is a SafeLoader subclass
  69. except yaml.YAMLError as err:
  70. return None, [f"config: invalid YAML ({type(err).__name__})"]
  71. def validate(text):
  72. """Return (stacks, problems): stacks maps each validated stack to its call args."""
  73. data, problems = load(text)
  74. if problems:
  75. return {}, problems
  76. if not isinstance(data, dict) or set(data) != {"version", "stacks"}:
  77. return {}, ["config: top level must be exactly version and stacks"]
  78. if not isinstance(data["stacks"], dict) or not data["stacks"]:
  79. return {}, ["config: stacks must be a non-empty mapping"]
  80. validated = {}
  81. for stack, hooks in data["stacks"].items():
  82. found = _check_stack(stack, hooks, problems)
  83. if found is not None:
  84. validated[stack] = found
  85. return validated, sorted(set(problems))
  86. def _check_stack(stack, hooks, problems):
  87. provider = provider_for(stack) if isinstance(stack, str) else None
  88. if provider is None:
  89. problems.append(f"{stack!r}: not a known stack name or cloud pattern")
  90. return None
  91. if not isinstance(hooks, dict) or set(hooks) != set(HOOKS):
  92. problems.append(f"{stack}: needs exactly before_init and before_apply")
  93. return None
  94. per_hook = {}
  95. for hook in HOOKS:
  96. before = len(problems)
  97. args = _check_hook(stack, provider, hook, hooks[hook], problems)
  98. if args is None or len(problems) != before:
  99. return None
  100. per_hook[hook] = args
  101. if per_hook["before_init"] != per_hook["before_apply"]:
  102. problems.append(f"{stack}: before_init and before_apply differ")
  103. return None
  104. return per_hook["before_init"]
  105. def _check_hook(stack, provider, hook, entries, problems):
  106. where = f"{stack}.{hook}"
  107. if not isinstance(entries, list) or len(entries) != 2:
  108. problems.append(
  109. f"{where}: must be the source line then one cah_doppler_env call"
  110. )
  111. return None
  112. source, call = entries
  113. if source != SOURCE_LINE:
  114. problems.append(f"{where}: first entry must be the doppler-env source line")
  115. return None
  116. if not isinstance(call, str) or not CALL_RE.fullmatch(call):
  117. problems.append(f"{where}: second entry is not a plain cah_doppler_env call")
  118. return None
  119. args = call.split()[1:]
  120. own = CLOUD_PREFIXES[provider]
  121. foreign = tuple(p for k, v in CLOUD_PREFIXES.items() if k != provider for p in v)
  122. for arg in args:
  123. var, _, src = arg.partition("=")
  124. src = src or var
  125. if var != src and not var.startswith("TF_VAR_"):
  126. problems.append(f"{where}: {var} is not TF_VAR_ or the secret's own name")
  127. for name in (var, src):
  128. bare = name.removeprefix("TF_VAR_").upper()
  129. if bare.startswith(foreign):
  130. problems.append(f"{where} ({provider}) requests {name}")
  131. if not (src.startswith(own) or src in SHARED_NAMES):
  132. problems.append(f"{where} ({provider}) requests unlisted {src}")
  133. return args
  134. def config_text(stacks, *, extra_top=""):
  135. """Build a config from {stack: [call, ...]}; each hook repeats the calls."""
  136. lines = ['version: "1"', extra_top, "stacks:"]
  137. for stack, calls in stacks.items():
  138. lines.append(f" {stack}:")
  139. for hook in HOOKS:
  140. lines += [f" {hook}:", f" - {SOURCE_LINE}"]
  141. lines += [f" - {call}" for call in calls]
  142. return "\n".join(lines) + "\n"
  143. def problems_for(stacks):
  144. return validate(config_text(stacks))[1]
  145. def code_lines(path):
  146. return "\n".join(
  147. line
  148. for line in path.read_text().splitlines()
  149. if not line.lstrip().startswith("#")
  150. )
  151. def test_real_config_passes_and_every_stack_was_validated():
  152. validated, problems = validate(CONFIG.read_text())
  153. assert problems == []
  154. raw = yaml.safe_load(CONFIG.read_text())["stacks"]
  155. assert set(validated) == set(raw) == {
  156. "cah-00-foundation",
  157. "cah-10-access",
  158. "cah-20-telemetry",
  159. }
  160. def test_stack_classification_is_explicit_and_fail_closed():
  161. assert provider_for("cah-00-foundation") == "digitalocean"
  162. assert provider_for("cah-aws-00-foundation") == "aws"
  163. assert provider_for("cah-azure-00-foundation") == "azure"
  164. assert provider_for("cah-gcp-00-foundation") == "gcp"
  165. for bad in (
  166. "cah-awsx-00",
  167. "cah-AWS-00",
  168. "CAH-AWS-00",
  169. "unrelated-stack",
  170. "aws-00",
  171. "cah-aws-",
  172. "cah-30-new",
  173. ):
  174. assert provider_for(bad) is None, bad
  175. assert any(
  176. "not a known stack name" in p
  177. for p in problems_for({bad: ["cah_doppler_env DIGITALOCEAN_TOKEN"]})
  178. )
  179. def test_cloud_prefixes_and_shared_names_are_disjoint():
  180. prefixes = [p for v in CLOUD_PREFIXES.values() for p in v]
  181. for name in SHARED_NAMES:
  182. assert not name.startswith(tuple(prefixes)), name
  183. for p in prefixes:
  184. assert p not in name, (name, p)
  185. for a in prefixes:
  186. for b in prefixes:
  187. assert a == b or not a.startswith(b), (a, b)
  188. @pytest.mark.parametrize(
  189. ("stack", "args", "expect"),
  190. [
  191. ("cah-00-foundation", "DIGITALOCEAN_TOKEN AWS_SECRET_ACCESS_KEY", "AWS_SECRET"),
  192. (
  193. "cah-aws-00-foundation",
  194. "AWS_ACCESS_KEY_ID DIGITALOCEAN_TOKEN",
  195. "DIGITALOCEAN",
  196. ),
  197. ("cah-azure-00-foundation", "ARM_CLIENT_SECRET GOOGLE_CREDENTIALS", "GOOGLE_"),
  198. ("cah-gcp-00-foundation", "GOOGLE_CREDENTIALS ARM_CLIENT_SECRET", "ARM_"),
  199. ("cah-aws-00-foundation", "TF_VAR_x=DIGITALOCEAN_TOKEN", "DIGITALOCEAN"),
  200. ("cah-aws-00-foundation", "AWS_X=GOOGLE_CREDENTIALS", "GOOGLE_"),
  201. ("cah-00-foundation", "ADMIN_AWS_SECRET_ACCESS_KEY", "unlisted ADMIN_AWS"),
  202. (
  203. "cah-aws-00-foundation",
  204. "ADMIN_DIGITALOCEAN_TOKEN",
  205. "unlisted ADMIN_DIGITALOCEAN",
  206. ),
  207. (
  208. "cah-00-foundation",
  209. "TWINGATE_AWS_SECRET_ACCESS_KEY",
  210. "unlisted TWINGATE_AWS",
  211. ),
  212. ("cah-00-foundation", "SLACK_WEBHOOK", "unlisted SLACK_WEBHOOK"),
  213. ],
  214. )
  215. def test_requesting_another_clouds_or_unlisted_secret_fails(stack, args, expect):
  216. found = problems_for({stack: [f"cah_doppler_env {args}"]})
  217. assert any(expect in p for p in found), found
  218. AWS_CALL = (
  219. "cah_doppler_env AWS_ACCESS_KEY_ID TWINGATE_API_TOKEN"
  220. " TF_VAR_admin_ssh_public_key=ADMIN_SSH_PUBLIC_KEY"
  221. )
  222. AWS_CALL = (
  223. "cah_doppler_env AWS_ACCESS_KEY_ID TWINGATE_API_TOKEN"
  224. " TF_VAR_admin_ssh_public_key=ADMIN_SSH_PUBLIC_KEY"
  225. )
  226. def test_own_and_shared_names_pass():
  227. assert (
  228. problems_for(
  229. {
  230. "cah-aws-10-access": [AWS_CALL],
  231. "cah-gcp-10-access": [
  232. "cah_doppler_env GOOGLE_CREDENTIALS TWINGATE_NETWORK"
  233. ],
  234. }
  235. )
  236. == []
  237. )
  238. def test_a_second_call_in_a_hook_is_not_hidden_by_the_last_one():
  239. found = problems_for(
  240. {
  241. "cah-aws-00-foundation": [
  242. "cah_doppler_env DIGITALOCEAN_TOKEN",
  243. "cah_doppler_env AWS_ACCESS_KEY_ID",
  244. ]
  245. }
  246. )
  247. assert any("must be the source line then one" in p for p in found), found
  248. def test_folded_scalar_call_is_parsed_not_skipped():
  249. text = 'version: "1"\nstacks:\n cah-aws-00-foundation:\n' + "".join(
  250. f" {h}:\n - {SOURCE_LINE}\n - >-\n"
  251. " cah_doppler_env\n DIGITALOCEAN_TOKEN\n"
  252. for h in HOOKS
  253. )
  254. assert any("DIGITALOCEAN" in p for p in validate(text)[1])
  255. def test_folded_scalar_plus_second_call_is_refused():
  256. text = 'version: "1"\nstacks:\n cah-aws-00-foundation:\n' + "".join(
  257. f" {h}:\n - {SOURCE_LINE}\n - >-\n"
  258. " cah_doppler_env\n DIGITALOCEAN_TOKEN\n"
  259. " - cah_doppler_env AWS_ACCESS_KEY_ID\n"
  260. for h in HOOKS
  261. )
  262. assert validate(text)[1]
  263. def test_anchor_and_alias_are_refused():
  264. text = (
  265. 'version: "1"\nx-evil: &evil cah_doppler_env DIGITALOCEAN_TOKEN\nstacks:\n'
  266. " cah-aws-00-foundation:\n"
  267. + "".join(f" {h}:\n - {SOURCE_LINE}\n - *evil\n" for h in HOOKS)
  268. )
  269. assert validate(text)[1] == ["config: anchors and aliases are not allowed"]
  270. @pytest.mark.parametrize("key", ['"CAH-AWS-00"', '"cah-aws-00"x', " cah-AWS-00"])
  271. def test_quoted_uppercase_or_odd_stack_keys_are_not_skipped(key):
  272. text = f'version: "1"\nstacks:\n {key.strip()}:\n' + "".join(
  273. f" {h}:\n - {SOURCE_LINE}\n - cah_doppler_env DIGITALOCEAN_TOKEN\n"
  274. for h in HOOKS
  275. )
  276. assert validate(text)[1], key
  277. def test_deeper_indentation_still_parsed_structurally():
  278. text = 'version: "1"\nstacks:\n cah-aws-00-foundation:\n' + "".join(
  279. f" {h}:\n - {SOURCE_LINE}\n - cah_doppler_env DIGITALOCEAN_TOKEN\n"
  280. for h in HOOKS
  281. )
  282. validated, problems = validate(text)
  283. assert any("DIGITALOCEAN" in p for p in problems)
  284. assert "cah-aws-00-foundation" not in validated
  285. def test_duplicate_stack_keys_are_refused():
  286. call = "cah_doppler_env DIGITALOCEAN_TOKEN"
  287. block = "".join(f" {h}:\n - {SOURCE_LINE}\n - {call}\n" for h in HOOKS)
  288. text = f'version: "1"\nstacks:\n cah-00-foundation:\n{block} cah-00-foundation:\n{block}'
  289. assert validate(text)[1]
  290. @pytest.mark.parametrize(
  291. "entry",
  292. [
  293. "cah_doppler_env DIGITALOCEAN_TOKEN; cah_doppler_env AWS_ACCESS_KEY_ID",
  294. "cah_doppler_env DIGITALOCEAN_TOKEN && echo $DOPPLER_TOKEN",
  295. "echo $DOPPLER_TOKEN",
  296. "cah_doppler_env",
  297. "cah_doppler_env 'DIGITALOCEAN_TOKEN'",
  298. "cah_doppler_env $X",
  299. ],
  300. )
  301. def test_unsupported_command_shapes_fail_closed(entry):
  302. assert problems_for({"cah-00-foundation": [entry]}), entry
  303. def test_non_string_and_missing_hooks_are_refused():
  304. for body in (
  305. " before_init: [1, 2]\n before_apply: [1, 2]\n",
  306. " before_init: []\n before_apply: []\n",
  307. f" before_init: [{SOURCE_LINE!r}]\n",
  308. " before_init: x\n before_apply: x\n",
  309. ):
  310. text = f'version: "1"\nstacks:\n cah-00-foundation:\n{body}'
  311. assert validate(text)[1], body
  312. def test_differing_hooks_and_extra_top_level_keys_are_refused():
  313. text = config_text({"cah-00-foundation": ["cah_doppler_env DIGITALOCEAN_TOKEN"]})
  314. parts = text.rsplit("cah_doppler_env DIGITALOCEAN_TOKEN", 1)
  315. assert any(
  316. "differ" in p
  317. for p in validate("cah_doppler_env TWINGATE_API_TOKEN".join(parts))[1]
  318. )
  319. assert validate(config_text({}, extra_top="x: 1"))[1]
  320. @pytest.mark.parametrize(
  321. ("stack", "old", "new"),
  322. [
  323. (
  324. "cah-00-foundation",
  325. "DIGITALOCEAN_TOKEN",
  326. "DIGITALOCEAN_TOKEN AWS_ACCESS_KEY_ID",
  327. ),
  328. (
  329. "cah-10-access",
  330. "DIGITALOCEAN_TOKEN",
  331. "DIGITALOCEAN_TOKEN GOOGLE_CREDENTIALS",
  332. ),
  333. ("cah-10-access", "ADMIN_USER_IDS", "ADMIN_USER_IDS ARM_CLIENT_SECRET"),
  334. ],
  335. )
  336. def test_mutating_the_real_config_text_is_caught(stack, old, new):
  337. text = CONFIG.read_text()
  338. start = text.index(f" {stack}:")
  339. end = text.find("\n cah-", start + 1)
  340. block = text[start : end if end != -1 else len(text)]
  341. mutated = text.replace(block, block.replace(old, new))
  342. assert mutated != text
  343. assert validate(mutated)[1]
  344. def test_script_takes_project_and_config_only_from_the_environment():
  345. code = code_lines(SCRIPT)
  346. assert not re.search(r"\bDOPPLER_(PROJECT|CONFIG|TOKEN)=", code)
  347. assert re.search(r'--project "\$DOPPLER_PROJECT"', code)
  348. assert re.search(r'--config "\$DOPPLER_CONFIG"', code)
  349. assert not re.search(r"--(project|config)\s+(?!\"\$DOPPLER_)\S", code)
  350. assert not re.search(r"(?<![/\w])(dev|prd)(_[a-z]+)?(?![/\w])", code)
  351. def test_config_does_not_set_doppler_context_variables():
  352. assert not re.search(r"DOPPLER_(PROJECT|CONFIG|TOKEN)", code_lines(CONFIG))