test_identifier_check.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. """Tests for scripts/identifier_check.py.
  2. Realistic-looking identifiers are assembled at run time from pieces, so this
  3. file does not itself contain one and the check passes over its own tests.
  4. """
  5. from __future__ import annotations
  6. import importlib.util
  7. import shutil
  8. import subprocess
  9. import sys
  10. import time
  11. from pathlib import Path
  12. import pytest
  13. SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "identifier_check.py"
  14. spec = importlib.util.spec_from_file_location("identifier_check", SCRIPT)
  15. ic = importlib.util.module_from_spec(spec)
  16. sys.modules["identifier_check"] = ic
  17. spec.loader.exec_module(ic)
  18. A = "2109" + "87654321"
  19. KEY = "Q7ZXCV" + "BNMASDFGHJ" # 16 characters
  20. SUB = "9c1e4b7a-" + "52d3-4f08-" + "a6b1-" + "3d7e90c2f845"
  21. G = "acme-" + "lab-" + "483920"
  22. Z = "00000000-0000-0000-0000-000000000000"
  23. AWS_ARN = "AWS ARN account id"
  24. AWS_ACCT = "AWS account id"
  25. AWS_KEY = "AWS access key id"
  26. AZ = "Azure subscription or tenant id"
  27. AZ_PATH = "Azure subscription id in a resource path"
  28. AZ_URL = "Azure tenant id in a sign-in URL"
  29. GCP = "GCP project id"
  30. GCP_PATH = "GCP project id in a resource path"
  31. REAL = [
  32. (AWS_ARN, f"arn:aws:iam::{A}:role/deployer"),
  33. (AWS_ARN, f" role = arn:aws:s3:eu-west-1:{A}:bucket/x"),
  34. (AWS_ARN, f"arn:aws:iam::{A}"),
  35. (AWS_ARN, f"ARN:AWS:IAM::{A}:root"),
  36. (AWS_ARN, f"<arn:aws:iam::<{A}>:role/x>"),
  37. (AWS_ACCT, f"account_id = {A}"),
  38. (AWS_ACCT, f'"aws_account": "{A}"'),
  39. (AWS_ACCT, f"Account ID: {A}"),
  40. (AWS_ACCT, f"account_number = {A}"),
  41. (AWS_ACCT, f"Account #{A}"),
  42. (AWS_ACCT, f"TF_VAR_aws_account_id={A}"),
  43. (AWS_ACCT, f"account_id = <{A}>"),
  44. (AWS_ACCT, f"<!-- account_id: <{A}> -->"),
  45. (AWS_ACCT, f"<https://console.aws.amazon.com/iam/home?account=<{A}>>"),
  46. (AWS_ACCT, f'<a href="https://x/?account=<{A}>">'),
  47. (AWS_ACCT, f"{A}.dkr.ecr.us-east-1.amazonaws.com/app:1"),
  48. (AWS_ACCT, f"https://{A}.signin.aws.amazon.com/console"),
  49. (AWS_ACCT, f'"OwnerId": "{A}"'),
  50. (AWS_KEY, f"key = AKIA{KEY}"),
  51. (AWS_KEY, f"k: ASIA{KEY}"),
  52. (AWS_KEY, f"AIDA{KEY}"),
  53. (AWS_KEY, f"AGPA{KEY}"),
  54. (AWS_KEY, f"ANPA{KEY}"),
  55. (AWS_KEY, f"ABIA{KEY}"),
  56. (AWS_KEY, f"AROA{KEY}"),
  57. (AWS_KEY, f"x_AKIA{KEY}"),
  58. (AZ, f'subscription_id = "{SUB}"'),
  59. (AZ, f"tenant_id: {SUB}"),
  60. (AZ, f"ARM_SUBSCRIPTION_ID={SUB}"),
  61. (AZ, f"ARM_TENANT_ID={SUB}"),
  62. (AZ, f"AZURE_TENANT_ID={SUB}"),
  63. (AZ, f'"homeTenantId": "{SUB}"'),
  64. (AZ, f'"id": "{SUB}"'),
  65. (AZ, f"subscription_id = <{SUB}>"),
  66. (AZ_PATH, f"/subscriptions/{SUB}/resourceGroups/rg"),
  67. (AZ_URL, f"https://login.microsoftonline.com/{SUB}/oauth2/v2.0/token"),
  68. (GCP, f'project_id = "{G}"'),
  69. (GCP, f"project: {G}"),
  70. (GCP, f'project = "{G}"'),
  71. (GCP, f" project = {G}"),
  72. (GCP, f"GOOGLE_PROJECT={G}"),
  73. (GCP, f"GOOGLE_CLOUD_PROJECT={G}"),
  74. (GCP, f"CLOUDSDK_CORE_PROJECT={G}"),
  75. (GCP, f"gcloud run deploy --project {G}"),
  76. (GCP, f"gcloud run deploy --project={G}"),
  77. (GCP, f"gcloud config set project {G}"),
  78. (GCP, f"https://console.cloud.google.com/home?project={G}"),
  79. (GCP_PATH, f"projects/{G}/locations/global"),
  80. ]
  81. SYNTHETIC = [
  82. "arn:aws:iam::123456789012:role/deployer",
  83. "arn:aws:iam::000000000000:root",
  84. "arn:aws:iam::<account-id>:role/x",
  85. "account_id = 111122223333",
  86. "Account ID: 123456789012",
  87. "aws_account = 000000000000",
  88. "account_number = 123456789012",
  89. "Account #111122223333",
  90. "TF_VAR_aws_account_id=123456789012",
  91. "account_id = <account-id>",
  92. "123456789012.dkr.ecr.us-east-1.amazonaws.com/app:1",
  93. "https://000000000000.signin.aws.amazon.com/console",
  94. '"OwnerId": "000000000000"',
  95. "AKIAIOSFODNN7EXAMPLE",
  96. "AIDAIOSFODNN7EXAMPLE",
  97. "AROAEXAMPLEEXAMPLE12",
  98. f"subscription_id = {Z}",
  99. "tenant_id = 11111111-1111-1111-1111-111111111111",
  100. f"ARM_SUBSCRIPTION_ID={Z}",
  101. f"ARM_TENANT_ID={Z}",
  102. f"AZURE_TENANT_ID={Z}",
  103. f'"homeTenantId": "{Z}"',
  104. f'"id": "{Z}"',
  105. f"/subscriptions/{Z}/resourceGroups/rg",
  106. f"https://login.microsoftonline.com/{Z}/oauth2/v2.0/token",
  107. "subscription_id = 9c1e4b7a-52d3-4f08-a6b1-example00000",
  108. "project_id = my-project-id",
  109. 'project_id = "your-project-id"',
  110. "project: project-id",
  111. 'project = "my-project-id"',
  112. "project = my-project-id",
  113. "GOOGLE_PROJECT=your-project-id",
  114. "GOOGLE_CLOUD_PROJECT=my-project-id",
  115. "CLOUDSDK_CORE_PROJECT=project-id",
  116. "gcloud run deploy --project my-project-id",
  117. "gcloud run deploy --project=your-project-id",
  118. "gcloud config set project my-project-id",
  119. "https://console.cloud.google.com/home?project=my-project-id",
  120. "projects/acme-example-123456/locations",
  121. "project = <your-project>",
  122. "project_id = var.project_id",
  123. "project_id = local.project",
  124. "project = digitalocean_project.main.id",
  125. "subscription_id = var.subscription_id",
  126. "Account 12345 is fine, and so is a bare " + "210987654321" + " with no label",
  127. "account_id = 2109876543210",
  128. "projects/1234",
  129. ]
  130. @pytest.mark.parametrize(("kind", "line"), REAL)
  131. def test_real_form_is_rejected(kind, line):
  132. assert kind in ic.scan_line(line)
  133. @pytest.mark.parametrize("line", SYNTHETIC)
  134. def test_synthetic_form_passes(line):
  135. assert ic.scan_line(line) == []
  136. def test_every_rule_has_a_red_fixture():
  137. """A rule nobody exercises could be deleted without a test noticing."""
  138. for index, (kind, pattern) in enumerate(ic.PATTERNS):
  139. hits = [
  140. line
  141. for k, line in REAL
  142. if k == kind
  143. and any(not ic.is_allowed(m.group("v")) for m in pattern.finditer(line))
  144. ]
  145. assert hits, f"no red fixture matches PATTERNS[{index}] ({kind})"
  146. def test_real_id_inside_angle_brackets_is_still_a_finding():
  147. for line in (f"account_id = <{A}>", f"<{A}>.dkr.ecr.eu-west-1.amazonaws.com"):
  148. assert ic.scan_line(line)
  149. MARKER_OK = [
  150. "account_id = {A} # identifier-check: ignore",
  151. "account_id = {A} // identifier-check: ignore because reasons",
  152. "<p>account_id: {A}</p> <!-- identifier-check: ignore -->",
  153. ]
  154. @pytest.mark.parametrize("template", MARKER_OK)
  155. def test_marker_in_a_trailing_comment_skips_the_line(template):
  156. assert ic.scan_line(template.format(A=A)) == []
  157. def test_marker_outside_a_comment_does_not_skip():
  158. assert ic.scan_line(f"https://x/identifier-check: ignore?account_id={A}")
  159. assert ic.scan_line(f"account_id = {A} identifier-check: ignore")
  160. def test_allow_list_is_the_documented_set():
  161. assert ic.ALLOWED_VALUES == {
  162. "123456789012",
  163. "000000000000",
  164. "111122223333",
  165. "00000000-0000-0000-0000-000000000000",
  166. "11111111-1111-1111-1111-111111111111",
  167. "my-project-id",
  168. "your-project-id",
  169. "project-id",
  170. }
  171. def seed(tmp_path: Path, rel: str, text: str = "", data: bytes | None = None) -> None:
  172. p = tmp_path / rel
  173. p.parent.mkdir(parents=True, exist_ok=True)
  174. if data is None:
  175. p.write_text(text, encoding="utf-8")
  176. else:
  177. p.write_bytes(data)
  178. def test_walk_reports_file_line_and_kind_without_any_value(tmp_path, capsys):
  179. seed(tmp_path, "docs/a.md", f"ok\nrole: arn:aws:iam::{A}:role/x\n")
  180. seed(tmp_path, "main.tf", f'project_id = "{G}"\n')
  181. seed(tmp_path, "clean.md", "account_id = 123456789012\n")
  182. assert ic.main(["--root", str(tmp_path)]) == 1
  183. out = capsys.readouterr().out
  184. assert "docs/a.md:2: AWS ARN account id" in out
  185. assert "main.tf:1: GCP project id" in out
  186. assert "clean.md" not in out
  187. for secret in (A, G, SUB, KEY, A[:2] + "..."):
  188. assert secret not in out
  189. def test_clean_tree_passes_and_reports_counts(tmp_path, capsys):
  190. seed(tmp_path, "a.md", "account_id = 123456789012\n")
  191. seed(tmp_path, "b.md", f"account_id = {A} # identifier-check: ignore\n")
  192. assert ic.main(["--root", str(tmp_path)]) == 0
  193. out = capsys.readouterr().out
  194. assert "passed" in out
  195. assert "2 files scanned" in out
  196. assert "1 ignore markers used" in out
  197. def test_plans_directory_and_vendor_dirs_are_skipped(tmp_path):
  198. line = f"account_id = {A}\n"
  199. seed(tmp_path, "docs/superpowers/plans/p.md", line)
  200. seed(tmp_path, ".terraform/x.txt", line)
  201. seed(tmp_path, ".venv/x.txt", line)
  202. seed(tmp_path, "ok.md", "nothing\n")
  203. assert ic.run(tmp_path).problems == []
  204. def test_latin1_file_is_scanned(tmp_path):
  205. seed(tmp_path, "l.txt", data=b"caf\xe9\naccount_id = " + A.encode() + b"\n")
  206. assert ic.run(tmp_path).problems == ["l.txt:2: AWS account id"]
  207. def test_invalid_utf8_stray_byte_does_not_hide_ids(tmp_path):
  208. seed(tmp_path, "s.txt", data=b"\xff\xff\n" + f"arn:aws:iam::{A}:root\n".encode())
  209. assert ic.run(tmp_path).problems == ["s.txt:2: AWS ARN account id"]
  210. @pytest.mark.parametrize("encoding", ["utf-16", "utf-16-le", "utf-16-be"])
  211. def test_utf16_file_with_bom_is_scanned(tmp_path, encoding):
  212. text = f"account_id = {A}\n"
  213. data = text.encode(encoding)
  214. if encoding != "utf-16":
  215. data = (b"\xff\xfe" if encoding.endswith("le") else b"\xfe\xff") + data
  216. seed(tmp_path, "u.txt", data=data)
  217. assert ic.run(tmp_path).problems == ["u.txt:1: AWS account id"]
  218. def test_file_over_one_megabyte_is_scanned(tmp_path):
  219. filler = ("x" * 99 + "\n") * 12000 # about 1.2 MB
  220. seed(tmp_path, "big.txt", filler + f"account_id = {A}\n")
  221. assert (tmp_path / "big.txt").stat().st_size > 1_000_000
  222. assert ic.run(tmp_path).problems == ["big.txt:12001: AWS account id"]
  223. def test_binary_file_is_counted_not_scanned(tmp_path, capsys):
  224. seed(tmp_path, "b.bin", data=b"\x89PNG\x00\x00" + A.encode())
  225. seed(tmp_path, "t.md", "hello\n")
  226. result = ic.run(tmp_path)
  227. assert result.problems == []
  228. assert result.binary == 1
  229. assert result.scanned == 1
  230. def test_oversize_file_fails_instead_of_skipping(tmp_path, monkeypatch):
  231. monkeypatch.setattr(ic, "MAX_BYTES", 10)
  232. seed(tmp_path, "huge.txt", "x" * 100)
  233. seed(tmp_path, "t.md", "hi\n")
  234. assert ic.main(["--root", str(tmp_path)]) == 1
  235. def test_missing_root_fails(tmp_path, capsys):
  236. assert ic.main(["--root", str(tmp_path / "nope")]) != 0
  237. assert "passed" not in capsys.readouterr().out
  238. def test_root_that_is_a_file_fails(tmp_path, capsys):
  239. seed(tmp_path, "f.txt", "x\n")
  240. assert ic.main(["--root", str(tmp_path / "f.txt")]) != 0
  241. assert "passed" not in capsys.readouterr().out
  242. def test_empty_root_fails(tmp_path, capsys):
  243. assert ic.main(["--root", str(tmp_path)]) != 0
  244. out = capsys.readouterr().out
  245. assert "passed" not in out
  246. assert "no files were scanned" in out
  247. @pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
  248. def test_tracked_files_are_used_inside_a_repo(tmp_path):
  249. subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)
  250. seed(tmp_path, "tracked.md", f"account_id = {A}\n")
  251. seed(tmp_path, "untracked.md", f"account_id = {A}\n")
  252. subprocess.run(["git", "-C", str(tmp_path), "add", "tracked.md"], check=True)
  253. assert ic.run(tmp_path).problems == ["tracked.md:1: AWS account id"]
  254. @pytest.mark.parametrize(
  255. "line",
  256. [
  257. "account" + " " * 20000,
  258. " " * 1_000_000,
  259. "account " * 100000,
  260. "project" + " " * 20000,
  261. "account" + " " * 20000 + "x",
  262. "account_id" + "\t" * 20000,
  263. "owner_id" + " " * 20000 + ":",
  264. 'project = "' + "a" * 20000,
  265. ],
  266. )
  267. def test_pathological_line_scans_fast(line):
  268. """Near-linear scan time, judged against a benign line of the same length.
  269. CPU time (not wall time) so a loaded machine cannot fail it, and a ratio
  270. against a same-run baseline so the bound scales with the machine. The
  271. scanner measures within about 2x of the baseline; quadratic or exponential
  272. backtracking is hundreds of times slower, so a bound of 25x still fails it.
  273. """
  274. def cpu_seconds(text: str) -> float:
  275. best = float("inf")
  276. for _ in range(3): # best of three drops scheduler noise
  277. start = time.process_time()
  278. ic.find_kinds(text)
  279. best = min(best, time.process_time() - start)
  280. return best
  281. baseline = cpu_seconds("x" * len(line))
  282. pathological = cpu_seconds(line)
  283. assert pathological <= 25 * max(baseline, 0.001), (
  284. f"{pathological:.3f}s CPU for a {len(line)}-character line, "
  285. f"benign baseline {baseline:.3f}s"
  286. )
  287. def test_the_repository_itself_is_clean():
  288. root = SCRIPT.parent.parent
  289. assert ic.main(["--root", str(root)]) == 0