identifier_check.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. #!/usr/bin/env python3
  2. """Identifier check for Clouds Against Humanity.
  3. This repository is public. The check scans every tracked text file for cloud
  4. account identifiers written in a structural form (an AWS ARN with an account
  5. id, an account id next to the word "account", an AWS key id, an Azure
  6. subscription or tenant id next to its key, a GCP project id next to its key)
  7. and fails when it finds one.
  8. It never prints the matched value, nor any part of it. A finding is reported
  9. as file:line and the kind, so the CI log does not become a second copy of the
  10. leak.
  11. It does not look for secrets. Secret scanning is Gitleaks' job; this catches
  12. identifiers that are not secrets but that a public repository should still
  13. not publish.
  14. Rules worth knowing:
  15. - Synthetic placeholders are allowed by name (ALLOWED_VALUES), and a value
  16. containing "example" is allowed. A placeholder like <account-id> is not an
  17. id-shaped value, so it never matches in the first place. A real id wrapped
  18. in angle brackets is still a finding.
  19. - A line may end with a comment carrying the ignore marker (see IGNORE_RE);
  20. the run prints how many were used.
  21. - A file that is not valid UTF-8 is decoded with replacement characters and
  22. scanned anyway. UTF-16 is decoded when it has a byte order mark. A file with
  23. NUL bytes and no byte order mark is binary and is counted, not scanned.
  24. - A bad root, or a run that scanned no file, fails.
  25. - docs/superpowers/plans is skipped.
  26. """
  27. from __future__ import annotations
  28. import argparse
  29. import re
  30. import subprocess
  31. import sys
  32. from pathlib import Path
  33. SKIP_DIRS = frozenset({".git", ".terraform", ".venv"})
  34. SKIP_PREFIXES = ("docs/superpowers/plans/",)
  35. # The marker counts only inside a comment at the end of the line.
  36. IGNORE_RE = re.compile(r"(?:#|//|<!--)[ \t]*identifier-check:[ \t]*ignore\b[^\n]*$")
  37. MAX_BYTES = 64_000_000
  38. BOMS = (b"\xff\xfe", b"\xfe\xff")
  39. # Synthetic values that lessons may show. Explicit on purpose: a realistic
  40. # looking 12-digit number is exactly what this check exists to refuse.
  41. ALLOWED_VALUES = frozenset(
  42. {
  43. "123456789012",
  44. "000000000000",
  45. "111122223333",
  46. "00000000-0000-0000-0000-000000000000",
  47. "11111111-1111-1111-1111-111111111111",
  48. "my-project-id",
  49. "your-project-id",
  50. "project-id",
  51. }
  52. )
  53. UUID = r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"
  54. GCP_ID = r"[a-z][a-z0-9-]{4,28}[a-z0-9]"
  55. KEYB = r"(?<![A-Za-z0-9])" # a key may follow "_" (TF_VAR_, ARM_), never a letter
  56. TAIL = r"(?![\w.\[(/$-])"
  57. TAIL_PATH = r"(?![\w.\[($-])"
  58. # Between a key and its value: optional quotes, ONE run of blanks, then an
  59. # optional ":" or "=". Only one blank-run quantifier is adjacent to another
  60. # optional piece, so a long run of spaces cannot cause backtracking blowup.
  61. OPT_SEP = r"[\"']?[ \t]*(?:[:=][ \t]*)?[\"'<]*"
  62. REQ_SEP = r"[\"']?[ \t]*[:=][ \t]*[\"'<]*"
  63. NOT_DIGIT_BEFORE = r"(?<!\d)"
  64. KEYS_PROJECT = r"(?i:" + KEYB + r"project(?:[_-]?id)?)"
  65. PREFIXES = "AKIA|ASIA|AIDA|AGPA|ANPA|ABIA|AROA|AIPA|ANVA|ACCA|APKA|ASCA"
  66. # (kind, compiled regex with the value in group "v")
  67. PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
  68. (
  69. "AWS ARN account id",
  70. re.compile(r"(?i)arn:aws[a-z-]*:[a-z0-9-]+:[a-z0-9-]*:<?(?P<v>\d{12})(?!\d)"),
  71. ),
  72. (
  73. "AWS account id",
  74. re.compile(
  75. r"(?i)" + KEYB + r"(?:aws[_ -]?account(?:[_ -]?(?:id|number))?"
  76. r"|account[_ -]?(?:id|number)|account(?:[ \t]?#)?)"
  77. + OPT_SEP
  78. + NOT_DIGIT_BEFORE
  79. + r"(?P<v>\d{12})(?!\d)"
  80. ),
  81. ),
  82. (
  83. "AWS account id",
  84. re.compile(
  85. r"(?i)"
  86. + NOT_DIGIT_BEFORE
  87. + r"<?(?P<v>\d{12})>?\.(?:dkr\.ecr[a-z0-9.-]*\.amazonaws\.com"
  88. r"|signin\.aws\.amazon\.com)"
  89. ),
  90. ),
  91. (
  92. "AWS account id",
  93. re.compile(
  94. r"(?i)"
  95. + KEYB
  96. + r"[\"']?owner[_-]?id"
  97. + REQ_SEP
  98. + NOT_DIGIT_BEFORE
  99. + r"(?P<v>\d{12})(?!\d)"
  100. ),
  101. ),
  102. (
  103. "AWS access key id",
  104. re.compile(
  105. rf"(?<![A-Za-z0-9])(?P<v>(?:{PREFIXES})[A-Z0-9]{{16}})(?![A-Za-z0-9])"
  106. ),
  107. ),
  108. (
  109. "Azure subscription or tenant id",
  110. re.compile(
  111. r"(?i)"
  112. + KEYB
  113. + r"(?:subscription[_-]?id|(?:home[_-]?)?tenant[_-]?id|[\"']id[\"'])"
  114. + REQ_SEP
  115. + rf"(?P<v>{UUID})\b"
  116. ),
  117. ),
  118. (
  119. "Azure subscription id in a resource path",
  120. re.compile(rf"(?i)/subscriptions/(?P<v>{UUID})\b"),
  121. ),
  122. (
  123. "Azure tenant id in a sign-in URL",
  124. re.compile(
  125. r"(?i)(?:login\.microsoftonline\.com|sts\.windows\.net)/"
  126. + rf"(?P<v>{UUID})\b"
  127. ),
  128. ),
  129. (
  130. "GCP project id",
  131. re.compile(
  132. KEYS_PROJECT + r"[\"']?[ \t]*[:=][ \t]*[\"']?" + rf"(?P<v>{GCP_ID}){TAIL}"
  133. ),
  134. ),
  135. (
  136. "GCP project id",
  137. re.compile(
  138. r"(?:--project(?:=|[ \t]+)|(?<![A-Za-z0-9])set[ \t]+project[ \t]+)[\"']?"
  139. + rf"(?P<v>{GCP_ID}){TAIL}"
  140. ),
  141. ),
  142. (
  143. "GCP project id in a resource path",
  144. re.compile(rf"(?<![A-Za-z0-9])projects/(?P<v>{GCP_ID}){TAIL_PATH}"),
  145. ),
  146. )
  147. def is_allowed(value: str) -> bool:
  148. return value.lower() in ALLOWED_VALUES or "example" in value.lower()
  149. def find_kinds(line: str) -> list[str]:
  150. """Kinds of every unallowed identifier on a line, ignoring any marker."""
  151. found: list[str] = []
  152. for kind, pattern in PATTERNS:
  153. for m in pattern.finditer(line):
  154. if not is_allowed(m.group("v")) and kind not in found:
  155. found.append(kind)
  156. return found
  157. def has_marker(line: str) -> bool:
  158. return IGNORE_RE.search(line) is not None
  159. def scan_line(line: str) -> list[str]:
  160. """Kinds found on a line; empty when the line carries a valid marker."""
  161. if has_marker(line):
  162. return []
  163. return find_kinds(line)
  164. def tracked_files(root: Path) -> list[Path]:
  165. try:
  166. out = subprocess.run(
  167. ["git", "-C", str(root), "ls-files", "-z"],
  168. check=True,
  169. capture_output=True,
  170. ).stdout
  171. names = [n for n in out.decode("utf-8", "replace").split("\0") if n]
  172. found = [root / n for n in names if (root / n).is_file()]
  173. if found:
  174. return found
  175. except (OSError, subprocess.CalledProcessError):
  176. pass
  177. files = []
  178. for path in sorted(root.rglob("*")):
  179. rel = path.relative_to(root)
  180. if SKIP_DIRS.intersection(rel.parts) or not path.is_file():
  181. continue
  182. files.append(path)
  183. return files
  184. class Result:
  185. def __init__(self) -> None:
  186. self.problems: list[str] = []
  187. self.scanned = 0
  188. self.binary = 0
  189. self.ignored = 0
  190. def decode(data: bytes) -> str | None:
  191. """Text of a file, or None when it is binary."""
  192. if data.startswith(BOMS):
  193. return data.decode("utf-16", errors="replace")
  194. if b"\0" in data:
  195. return None
  196. return data.decode("utf-8", errors="replace")
  197. def scan_file(path: Path, rel: str, result: Result) -> None:
  198. try:
  199. size = path.stat().st_size
  200. if size > MAX_BYTES:
  201. result.problems.append(
  202. f"{rel}: not scanned, file is larger than {MAX_BYTES} bytes"
  203. )
  204. return
  205. text = decode(path.read_bytes())
  206. except OSError:
  207. result.problems.append(f"{rel}: not scanned, could not be read")
  208. return
  209. if text is None:
  210. result.binary += 1
  211. return
  212. result.scanned += 1
  213. for number, line in enumerate(text.splitlines(), start=1):
  214. kinds = find_kinds(line)
  215. if not kinds:
  216. continue
  217. if has_marker(line):
  218. result.ignored += 1
  219. continue
  220. for kind in kinds:
  221. result.problems.append(f"{rel}:{number}: {kind}")
  222. def run(root: Path) -> Result:
  223. result = Result()
  224. for path in tracked_files(root):
  225. rel = path.relative_to(root).as_posix()
  226. if rel.startswith(SKIP_PREFIXES):
  227. continue
  228. scan_file(path, rel, result)
  229. return result
  230. def main(argv: list[str] | None = None) -> int:
  231. parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
  232. parser.add_argument("--root", default=".", help="repository root")
  233. args = parser.parse_args(argv)
  234. root = Path(args.root).resolve()
  235. if not root.is_dir():
  236. print(f"identifier check FAILED: root is not a directory: {args.root}")
  237. return 2
  238. result = run(root)
  239. summary = (
  240. f"{result.scanned} files scanned, {result.binary} binary skipped, "
  241. f"{result.ignored} ignore markers used"
  242. )
  243. if result.scanned == 0:
  244. print(f"identifier check FAILED: no files were scanned ({summary})")
  245. return 1
  246. if result.problems:
  247. print("identifier check FAILED (values are never printed):")
  248. for p in result.problems:
  249. print(f" {p}")
  250. print(summary)
  251. print(
  252. "Use a synthetic placeholder (see ALLOWED_VALUES in "
  253. "scripts/identifier_check.py) or end the line with a comment "
  254. "'identifier-check: ignore'."
  255. )
  256. return 1
  257. print(f"identifier check passed ({summary})")
  258. return 0
  259. if __name__ == "__main__":
  260. sys.exit(main())