check_manifests.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. #!/usr/bin/env python3
  2. """Cluster-manifest policy lint (task 46).
  3. Validates `deploy/k8s` (and `compose.yaml` lightly) against the cluster
  4. contract WITHOUT a live cluster:
  5. - Deployment: 3 replicas, non-root 65532, read-only rootfs, RuntimeDefault
  6. seccomp, ALL capabilities dropped, requests+limits, startup/liveness on
  7. `/health/live` + readiness on `/health/ready` via httpGet against the
  8. plaintext health port (8081), `terminationGracePeriodSeconds >= 45`,
  9. topology spread, and NO per-replica migration.
  10. - Migration Job: exactly one, runs `migrate`, `restartPolicy: Never`.
  11. - PDB: `minAvailable: 2`.
  12. - Service: never exposes the health port (8081).
  13. - Hardening: `automountServiceAccountToken: false` and `fsGroup: 65532`; every
  14. secret (token pepper, TOTP key, database and Redis passwords) must be
  15. file-mounted from `d-oauth-secrets` at `/run/secrets` (`defaultMode: 0400`)
  16. and referenced with its `*_FILE` variable; the inline
  17. `D_OAUTH_TOKEN_PEPPER` / `D_OAUTH_TOTP_ENCRYPTION_KEY` envs FAIL, and any
  18. workload env that injects a secret FAILS (`secretKeyRef`, `envFrom.secretRef`,
  19. a literal value embedding a DSN password, or a workload redefinition of
  20. `D_OAUTH_DATABASE__URL` / `D_OAUTH_REDIS__URL`).
  21. - ConfigMap: the ConfigMap referenced by a workload `envFrom` must provide the
  22. passwordless `D_OAUTH_DATABASE__URL` / `D_OAUTH_REDIS__URL` DSNs, and neither
  23. may embed a password (it belongs in the Secret, read through the
  24. `*_PASSWORD_FILE` form).
  25. - NetworkPolicy: must select `app.kubernetes.io/name: d-oauth-server`, enable
  26. `Ingress` + `Egress`, admit ingress only on 8080/8081, and allow egress only
  27. on 53 (DNS), 5432 (Postgres), and 6379 (Redis) with `169.254.0.0/16`
  28. excluded (cloud metadata).
  29. - No baked secrets: no PEM blocks in manifests; `REPLACE_ME` placeholders
  30. only inside `secret.yaml`; no secret-shaped keys in the ConfigMap.
  31. - L7-vs-L4 mTLS constraint: an L7 Ingress that terminates TLS while
  32. in-process client-cert auth is enabled (`D_OAUTH_TLS__CLIENT_CA_PATH`
  33. set, or client-cert Ingress annotations) FAILS. mTLS needs L4/TCP
  34. passthrough (NLB gateway / TLSRoute) or explicit trusted-proxy mode.
  35. This constraint is DOCUMENTED (docs/DEPLOYMENT.md) and lint-checked
  36. here; it is explicitly NOT exercised end-to-end in CI.
  37. Usage:
  38. python3 scripts/check_manifests.py [--manifest-dir deploy/k8s]
  39. [--strict-digest]
  40. `--strict-digest` (used by supply-chain CI after the pin step) additionally
  41. requires every workload image to be digest-pinned (`@sha256:<64 hex>`).
  42. """
  43. from __future__ import annotations
  44. import argparse
  45. import re
  46. import sys
  47. from pathlib import Path
  48. import yaml
  49. HEALTH_PORT = 8081
  50. PUBLIC_PORT = 8080
  51. TERMINATION_GRACE_MIN = 45
  52. SECRET_NAME_RE = re.compile(r"(?i)(pepper|password|secret|private[_-]?key|totp)")
  53. PEM_RE = re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----|-----BEGIN CERTIFICATE-----")
  54. DIGEST_RE = re.compile(r"@sha256:[0-9a-f]{64}$")
  55. HIGH_ENTROPY_VALUE_RE = re.compile(r"^[A-Za-z0-9+/=_-]{32,}$")
  56. # A DSN that carries `user:password@` (or `:password@`) embeds a credential.
  57. EMBEDDED_PASSWORD_RE = re.compile(r"://[^/@?#]*:[^/@?#]*@")
  58. CLIENT_CERT_ANNOTATIONS = (
  59. "nginx.ingress.kubernetes.io/auth-tls-verify-client",
  60. "nginx.ingress.kubernetes.io/auth-tls-secret",
  61. "haproxy.org/ssl-verify-client",
  62. "traefik.ingress.kubernetes.io/router.tls.options",
  63. )
  64. SECRET_NAME = "d-oauth-secrets"
  65. SECRETS_MOUNT_PATH = "/run/secrets"
  66. FS_GROUP = 65532
  67. SECRET_VOLUME_MODE = 0o400
  68. FILE_SECRET_ENV_KEYS = {
  69. "D_OAUTH_TOKEN_PEPPER_FILE": "token-pepper",
  70. "D_OAUTH_TOTP_ENCRYPTION_KEY_FILE": "totp-encryption-key",
  71. "D_OAUTH_DATABASE__PASSWORD_FILE": "database-password",
  72. "D_OAUTH_REDIS__PASSWORD_FILE": "redis-password",
  73. }
  74. INLINE_SECRET_ENVS = ("D_OAUTH_TOKEN_PEPPER", "D_OAUTH_TOTP_ENCRYPTION_KEY")
  75. PASSWORDLESS_DSN_KEYS = ("D_OAUTH_DATABASE__URL", "D_OAUTH_REDIS__URL")
  76. REQUIRED_EGRESS_PORTS = (53, 5432, 6379)
  77. METADATA_CIDR = "169.254.0.0/16"
  78. class Failures:
  79. def __init__(self) -> None:
  80. self.items: list[str] = []
  81. def add(self, msg: str) -> None:
  82. self.items.append(msg)
  83. def ok(self) -> bool:
  84. return not self.items
  85. def load_manifests(manifest_dir: Path) -> tuple[list[dict], Failures]:
  86. fails = Failures()
  87. docs: list[dict] = []
  88. files = sorted(manifest_dir.glob("*.yaml"))
  89. if not files:
  90. fails.add(f"no manifests found in {manifest_dir}")
  91. return docs, fails
  92. for path in files:
  93. if path.name.endswith(".example.yaml"):
  94. continue
  95. try:
  96. loaded = list(yaml.safe_load_all(path.read_text()))
  97. except yaml.YAMLError as exc:
  98. fails.add(f"{path.name}: invalid YAML: {exc}")
  99. continue
  100. for doc in loaded:
  101. if doc:
  102. doc["_source"] = path.name
  103. docs.append(doc)
  104. return docs, fails
  105. def by_kind(docs: list[dict], kind: str) -> list[dict]:
  106. return [d for d in docs if d.get("kind") == kind]
  107. def check_pem_and_placeholders(docs: list[dict], fails: Failures) -> None:
  108. for doc in docs:
  109. src = doc.get("_source", "?")
  110. text = yaml.safe_dump({k: v for k, v in doc.items() if not k.startswith("_")})
  111. if PEM_RE.search(text):
  112. fails.add(f"{src}: baked key material (PEM block) in a manifest")
  113. if src != "secret.yaml" and "REPLACE_ME" in text:
  114. fails.add(f"{src}: placeholder belongs only in secret.yaml")
  115. def check_configmap(doc: dict, fails: Failures, requires_dsn: bool) -> None:
  116. data = doc.get("data") or {}
  117. for key in data:
  118. if SECRET_NAME_RE.search(key):
  119. fails.add(f"configmap: secret-shaped key {key!r} must live in the Secret")
  120. if not requires_dsn:
  121. return
  122. for key in PASSWORDLESS_DSN_KEYS:
  123. value = (data.get(key) or "").strip()
  124. if not value:
  125. fails.add(
  126. f"configmap: {key} is required; the workloads take the DSN from here "
  127. "and the password from the mounted *_PASSWORD_FILE"
  128. )
  129. elif EMBEDDED_PASSWORD_RE.search(value):
  130. fails.add(
  131. f"configmap: {key} must not embed a password; move it to the Secret "
  132. "and use the *_PASSWORD_FILE form"
  133. )
  134. def referenced_configmaps(docs: list[dict]) -> set[str]:
  135. """Names of ConfigMaps any workload pulls into the environment via `envFrom`."""
  136. names: set[str] = set()
  137. for kind in ("Deployment", "Job"):
  138. for doc in by_kind(docs, kind):
  139. tpl = (doc.get("spec") or {}).get("template", {}).get("spec", {})
  140. for container in tpl.get("containers") or []:
  141. for ref in container.get("envFrom") or []:
  142. name = ((ref or {}).get("configMapRef") or {}).get("name")
  143. if name:
  144. names.add(name)
  145. return names
  146. def mtls_enabled(docs: list[dict]) -> bool:
  147. for doc in by_kind(docs, "ConfigMap"):
  148. data = doc.get("data") or {}
  149. if (data.get("D_OAUTH_TLS__CLIENT_CA_PATH") or "").strip():
  150. return True
  151. return False
  152. def octal_mode(value: object) -> int | None:
  153. """Parse a YAML file mode (`0400`, `0o400`, `256`) into an int, or None."""
  154. if isinstance(value, bool) or value is None:
  155. return None
  156. if isinstance(value, int):
  157. return value
  158. if isinstance(value, str):
  159. text = value.strip().lower().replace("_", "")
  160. try:
  161. if text.startswith("0o"):
  162. return int(text[2:], 8)
  163. if text.startswith("0") and len(text) > 1:
  164. return int(text, 8)
  165. return int(text, 10)
  166. except ValueError:
  167. return None
  168. return None
  169. def env_by_name(container: dict) -> dict[str, dict]:
  170. envs: dict[str, dict] = {}
  171. for entry in container.get("env") or []:
  172. if isinstance(entry, dict) and entry.get("name"):
  173. envs[entry["name"]] = entry
  174. return envs
  175. def check_file_mounted_secrets(
  176. workload: str, tpl: dict, container: dict, fails: Failures
  177. ) -> None:
  178. """Item 7: pepper/TOTP are 0400 files under /run/secrets, never inline env."""
  179. cname = container.get("name", "?")
  180. envs = env_by_name(container)
  181. for ref in container.get("envFrom") or []:
  182. if isinstance(ref, dict) and "secretRef" in ref:
  183. fails.add(
  184. f"{workload}/{cname}: envFrom.secretRef injects every secret into the "
  185. "environment; mount the keys as files instead"
  186. )
  187. for name, entry in envs.items():
  188. if "secretKeyRef" in (entry.get("valueFrom") or {}):
  189. fails.add(
  190. f"{workload}/{cname}: env {name} injects a secret via secretKeyRef; "
  191. "mount it as a file and reference the *_FILE form"
  192. )
  193. if name in PASSWORDLESS_DSN_KEYS:
  194. fails.add(
  195. f"{workload}/{cname}: {name} must come from the ConfigMap, not the "
  196. "workload env (an inline value could embed a password)"
  197. )
  198. value = entry.get("value")
  199. if isinstance(value, str) and EMBEDDED_PASSWORD_RE.search(value):
  200. fails.add(
  201. f"{workload}/{cname}: env {name} embeds a password; mount it as a file"
  202. )
  203. for inline in INLINE_SECRET_ENVS:
  204. if inline in envs:
  205. fails.add(
  206. f"{workload}/{cname}: {inline} must not be injected as an env value; "
  207. "use the file-mounted *_FILE form"
  208. )
  209. mount = next(
  210. (
  211. m
  212. for m in container.get("volumeMounts") or []
  213. if isinstance(m, dict) and m.get("mountPath") == SECRETS_MOUNT_PATH
  214. ),
  215. None,
  216. )
  217. if mount is None:
  218. fails.add(
  219. f"{workload}/{cname}: must mount the secret volume at {SECRETS_MOUNT_PATH}"
  220. )
  221. elif mount.get("readOnly") is not True:
  222. fails.add(f"{workload}/{cname}: {SECRETS_MOUNT_PATH} must be readOnly")
  223. items: dict[str, str] = {}
  224. mode: int | None = None
  225. for volume in tpl.get("volumes") or []:
  226. if not isinstance(volume, dict):
  227. continue
  228. secret = volume.get("secret") or {}
  229. if secret.get("secretName") != SECRET_NAME:
  230. continue
  231. mode = octal_mode(secret.get("defaultMode"))
  232. for item in secret.get("items") or []:
  233. if isinstance(item, dict) and item.get("key") and item.get("path"):
  234. items[item["key"]] = item["path"]
  235. if mode != SECRET_VOLUME_MODE:
  236. fails.add(f"{workload}: {SECRET_NAME} volume defaultMode must be 0400")
  237. for env_name, key in FILE_SECRET_ENV_KEYS.items():
  238. if key not in items:
  239. fails.add(f"{workload}: {SECRET_NAME} volume must project key {key!r}")
  240. continue
  241. expected = f"{SECRETS_MOUNT_PATH}/{items[key]}"
  242. entry = envs.get(env_name) or {}
  243. if (entry.get("value") or "").strip() != expected:
  244. fails.add(f"{workload}/{cname}: {env_name} must point at {expected}")
  245. def policy_ports(rule: dict) -> set[int]:
  246. ports: set[int] = set()
  247. for port in rule.get("ports") or []:
  248. if isinstance(port, dict) and isinstance(port.get("port"), int):
  249. ports.add(port["port"])
  250. return ports
  251. def check_networkpolicy(doc: dict, fails: Failures) -> None:
  252. """Item 9: default-deny ingress/egress for the app pods."""
  253. name = doc.get("metadata", {}).get("name", "?")
  254. spec = doc.get("spec") or {}
  255. selector = (spec.get("podSelector") or {}).get("matchLabels") or {}
  256. if selector.get("app.kubernetes.io/name") != "d-oauth-server":
  257. fails.add(
  258. f"networkpolicy/{name}: podSelector must match "
  259. "app.kubernetes.io/name: d-oauth-server"
  260. )
  261. if not {"Ingress", "Egress"} <= set(spec.get("policyTypes") or []):
  262. fails.add(f"networkpolicy/{name}: policyTypes must include Ingress and Egress")
  263. ingress_ports: set[int] = set()
  264. for rule in spec.get("ingress") or []:
  265. if isinstance(rule, dict):
  266. ingress_ports |= policy_ports(rule)
  267. if not {PUBLIC_PORT, HEALTH_PORT} <= ingress_ports:
  268. fails.add(
  269. f"networkpolicy/{name}: ingress must admit ports "
  270. f"{PUBLIC_PORT} and {HEALTH_PORT}"
  271. )
  272. egress_ports: set[int] = set()
  273. metadata_excluded = False
  274. for rule in spec.get("egress") or []:
  275. if not isinstance(rule, dict):
  276. continue
  277. egress_ports |= policy_ports(rule)
  278. for peer in rule.get("to") or []:
  279. block = (peer or {}).get("ipBlock") or {}
  280. if METADATA_CIDR in (block.get("except") or []):
  281. metadata_excluded = True
  282. for port in REQUIRED_EGRESS_PORTS:
  283. if port not in egress_ports:
  284. fails.add(f"networkpolicy/{name}: egress must allow port {port}")
  285. if not metadata_excluded:
  286. fails.add(
  287. f"networkpolicy/{name}: egress must exclude {METADATA_CIDR} (cloud metadata)"
  288. )
  289. def check_deployment(doc: dict, fails: Failures, strict_digest: bool) -> None:
  290. name = doc.get("metadata", {}).get("name", "?")
  291. spec = doc.get("spec", {})
  292. if spec.get("replicas") != 3:
  293. fails.add(f"deployment/{name}: replicas must be 3")
  294. tpl = spec.get("template", {}).get("spec", {})
  295. if tpl.get("terminationGracePeriodSeconds", 0) < TERMINATION_GRACE_MIN:
  296. fails.add(f"deployment/{name}: terminationGracePeriodSeconds must be >= 45")
  297. pod_sc = tpl.get("securityContext", {})
  298. if pod_sc.get("runAsNonRoot") is not True:
  299. fails.add(f"deployment/{name}: runAsNonRoot must be true")
  300. if pod_sc.get("runAsUser") != 65532:
  301. fails.add(f"deployment/{name}: runAsUser must be 65532")
  302. if (pod_sc.get("seccompProfile") or {}).get("type") != "RuntimeDefault":
  303. fails.add(f"deployment/{name}: seccompProfile.type must be RuntimeDefault")
  304. if tpl.get("automountServiceAccountToken") is not False:
  305. fails.add(f"deployment/{name}: automountServiceAccountToken must be false")
  306. if pod_sc.get("fsGroup") != FS_GROUP:
  307. fails.add(
  308. f"deployment/{name}: fsGroup must be {FS_GROUP} so the 0400 secret "
  309. "files are readable by the runtime user"
  310. )
  311. if not tpl.get("topologySpreadConstraints"):
  312. fails.add(f"deployment/{name}: topologySpreadConstraints required")
  313. for container in tpl.get("containers", []):
  314. cname = container.get("name", "?")
  315. csc = container.get("securityContext", {})
  316. if csc.get("readOnlyRootFilesystem") is not True:
  317. fails.add(f"deployment/{name}/{cname}: readOnlyRootFilesystem must be true")
  318. if "ALL" not in (csc.get("capabilities") or {}).get("drop", []):
  319. fails.add(f"deployment/{name}/{cname}: capabilities.drop must include ALL")
  320. res = container.get("resources", {})
  321. if not res.get("requests") or not res.get("limits"):
  322. fails.add(f"deployment/{name}/{cname}: requests and limits required")
  323. args = " ".join(
  324. str(a)
  325. for a in (
  326. list(container.get("command", [])) + list(container.get("args", []))
  327. )
  328. )
  329. if "migrate" in args:
  330. fails.add(f"deployment/{name}/{cname}: replicas must never migrate")
  331. probes = {
  332. "startupProbe": ("/health/live", True),
  333. "livenessProbe": ("/health/live", True),
  334. "readinessProbe": ("/health/ready", True),
  335. }
  336. for probe_name, (path, _) in probes.items():
  337. probe = container.get(probe_name) or {}
  338. http_get = probe.get("httpGet") or {}
  339. if http_get.get("path") != path or http_get.get("port") != HEALTH_PORT:
  340. fails.add(
  341. f"deployment/{name}/{cname}: {probe_name} must httpGet "
  342. f"{path} on port {HEALTH_PORT} (plaintext health listener)"
  343. )
  344. image = container.get("image", "")
  345. if strict_digest and not DIGEST_RE.search(image):
  346. fails.add(f"deployment/{name}/{cname}: image must be digest-pinned")
  347. check_file_mounted_secrets(f"deployment/{name}", tpl, container, fails)
  348. def check_job(doc: dict, fails: Failures, strict_digest: bool) -> None:
  349. name = doc.get("metadata", {}).get("name", "?")
  350. spec = doc.get("spec", {}).get("template", {}).get("spec", {})
  351. if spec.get("restartPolicy") != "Never":
  352. fails.add(f"job/{name}: restartPolicy must be Never")
  353. if spec.get("automountServiceAccountToken") is not False:
  354. fails.add(f"job/{name}: automountServiceAccountToken must be false")
  355. if (spec.get("securityContext") or {}).get("fsGroup") != FS_GROUP:
  356. fails.add(
  357. f"job/{name}: fsGroup must be {FS_GROUP} so the 0400 secret files are "
  358. "readable by the runtime user"
  359. )
  360. containers = spec.get("containers", [])
  361. if not any(
  362. "migrate" in " ".join(str(a) for a in (list(c.get("command", [])) + list(c.get("args", []))))
  363. for c in containers
  364. ):
  365. fails.add(f"job/{name}: exactly one migrate Job must run `/d-oauth-server migrate`")
  366. for container in containers:
  367. if strict_digest and not DIGEST_RE.search(container.get("image", "")):
  368. fails.add(f"job/{name}: image must be digest-pinned")
  369. check_file_mounted_secrets(f"job/{name}", spec, container, fails)
  370. def check_pdb(doc: dict, fails: Failures) -> None:
  371. if doc.get("spec", {}).get("minAvailable") != 2:
  372. fails.add("poddisruptionbudget: minAvailable must be 2")
  373. def check_service(doc: dict, fails: Failures) -> None:
  374. ports = doc.get("spec", {}).get("ports", [])
  375. exposed = {p.get("port") for p in ports} | {p.get("targetPort") for p in ports}
  376. if HEALTH_PORT in exposed:
  377. fails.add("service: must not expose the plaintext health port 8081")
  378. def check_l7_mtls(docs: list[dict], fails: Failures) -> None:
  379. """An L7 ingress that terminates TLS strips the client certificate."""
  380. ingresses = by_kind(docs, "Ingress")
  381. if not ingresses:
  382. return
  383. client_auth = mtls_enabled(docs)
  384. for ing in ingresses:
  385. name = ing.get("metadata", {}).get("name", "?")
  386. annotations = (ing.get("metadata", {}) or {}).get("annotations", {}) or {}
  387. terminates = bool((ing.get("spec", {}) or {}).get("tls"))
  388. wants_client_cert = client_auth or any(a in annotations for a in CLIENT_CERT_ANNOTATIONS)
  389. if terminates and wants_client_cert:
  390. fails.add(
  391. f"ingress/{name}: L7 TLS termination strips the client certificate "
  392. "while in-process client-cert auth is enabled — use L4/TCP "
  393. "passthrough (NLB gateway / TLSRoute) or explicit trusted-proxy mode"
  394. )
  395. def main() -> int:
  396. parser = argparse.ArgumentParser()
  397. parser.add_argument("--manifest-dir", default="deploy/k8s")
  398. parser.add_argument("--strict-digest", action="store_true")
  399. args = parser.parse_args()
  400. fails = Failures()
  401. docs, load_fails = load_manifests(Path(args.manifest_dir))
  402. fails.items.extend(load_fails.items)
  403. kinds = {d.get("kind") for d in docs}
  404. for required in (
  405. "Deployment",
  406. "Service",
  407. "ConfigMap",
  408. "Secret",
  409. "Job",
  410. "PodDisruptionBudget",
  411. "NetworkPolicy",
  412. ):
  413. if required not in kinds:
  414. fails.add(f"missing required kind: {required}")
  415. check_pem_and_placeholders(docs, fails)
  416. required_dsn_configmaps = referenced_configmaps(docs)
  417. for doc in by_kind(docs, "ConfigMap"):
  418. name = (doc.get("metadata") or {}).get("name")
  419. check_configmap(doc, fails, requires_dsn=name in required_dsn_configmaps)
  420. for doc in by_kind(docs, "Deployment"):
  421. check_deployment(doc, fails, args.strict_digest)
  422. for doc in by_kind(docs, "Job"):
  423. check_job(doc, fails, args.strict_digest)
  424. for doc in by_kind(docs, "PodDisruptionBudget"):
  425. check_pdb(doc, fails)
  426. for doc in by_kind(docs, "Service"):
  427. check_service(doc, fails)
  428. for doc in by_kind(docs, "NetworkPolicy"):
  429. check_networkpolicy(doc, fails)
  430. check_l7_mtls(docs, fails)
  431. if fails.ok():
  432. print(f"manifest lint: OK ({len(docs)} documents, strict-digest={args.strict_digest})")
  433. return 0
  434. print(f"manifest lint: {len(fails.items)} failure(s):")
  435. for item in fails.items:
  436. print(f" - {item}")
  437. return 1
  438. if __name__ == "__main__":
  439. sys.exit(main())