check_manifests.py 21 KB

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