check_manifests.py 20 KB

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