Files
platform-core/scripts/validate/render-tenants-and-policies.sh
T
DongHyeonka ebdf33f072 feat(tenants): declare the tech-log objects inside platform namespaces
The tech-log tenant needs objects inside platform namespaces: its
database and role, ingress to Postgres and AIStor, blackbox probes,
alert rules, a dashboard and two observability NetworkPolicies. They
were only ever applied with kubectl and no repository holds them, so a
deleted object cannot be recreated and a platform re-apply can drop
tech-log access without anyone noticing.

Declare them in services/tenants/techlog, copied from each object's
last-applied configuration. The dashboard follows the repository's
dashboard pattern (JSON file + configMapGenerator, same name, same
labels). The hyeonworks-prod Namespace moves here as the tenant
boundary and gets PSA enforce=baseline, warn/audit=restricted.

Rejected: enforce=restricted now. A server dry-run shows all three
tech-log pods would violate it; baseline has zero violations.

Risk: the render matches the live objects exactly except the added PSA
labels. The pg_hba rules and the Secret stay out of this root (Cluster
owner and Git policy).

Verification (desktop):
- render-tenants-and-policies.sh passes.
- kubectl diff of the render shows only the Namespace PSA labels.
- kubectl label --dry-run=server enforce=baseline: no warnings.
2026-11-12 00:29:18 +09:00

127 lines
5.9 KiB
Bash

#!/usr/bin/env bash
# Render the tech-log tenant root, the platform PriorityClasses and the keycloak
# namespace NetworkPolicies, and check their invariants. Static: no cluster access.
set -Eeuo pipefail
readonly EXPECTED_KUSTOMIZE_VERSION="v5.8.1"
readonly REPOSITORY_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"
fail() {
printf 'ERROR: %s\n' "$*" >&2
exit 1
}
kustomize_version="$(kubectl version --client --output=yaml | sed -n 's/^kustomizeVersion: //p')"
[[ "$kustomize_version" == "$EXPECTED_KUSTOMIZE_VERSION" ]] || \
fail "expected Kustomize ${EXPECTED_KUSTOMIZE_VERSION}, found ${kustomize_version:-unknown}"
work="$(mktemp -d "${TMPDIR:-/tmp}/platform-tenants-render.XXXXXX")"
trap 'rm -rf -- "$work"' EXIT
kubectl kustomize "$REPOSITORY_ROOT/services/tenants/techlog" >"$work/techlog.yaml"
kubectl kustomize "$REPOSITORY_ROOT/services/priority-classes" >"$work/priority-classes.yaml"
kubectl kustomize "$REPOSITORY_ROOT/infrastructure/networking/keycloak" >"$work/keycloak-network-policies.yaml"
python3 -I - "$work" <<'PY'
import sys, pathlib, yaml
work = pathlib.Path(sys.argv[1])
errors = []
def load(name):
return [d for d in yaml.safe_load_all((work / name).read_text()) if d]
def keyset(docs):
return sorted((d["kind"], d["metadata"].get("namespace", ""), d["metadata"]["name"]) for d in docs)
for name in ("techlog.yaml", "priority-classes.yaml", "keycloak-network-policies.yaml"):
for d in load(name):
if d["kind"] == "Secret":
errors.append(f"{name}: Secret objects must not be rendered")
techlog = load("techlog.yaml")
expected = sorted([
("Namespace", "", "hyeonworks-prod"),
("Database", "platform-data", "platform-postgres-techlog"),
("DatabaseRole", "platform-data", "platform-postgres-techlog"),
("NetworkPolicy", "platform-data", "allow-techlog-backend"),
("NetworkPolicy", "object-storage", "allow-techlog-backend"),
("Probe", "observability", "techlog-edge"),
("Probe", "observability", "techlog-readiness"),
("PrometheusRule", "observability", "techlog"),
("ConfigMap", "observability", "grafana-dashboard-techlog"),
("NetworkPolicy", "observability", "blackbox-allow-techlog-health"),
("NetworkPolicy", "observability", "observability-allow-techlog-scrape"),
])
if keyset(techlog) != expected:
errors.append(f"tech-log tenant objects differ: {keyset(techlog)}")
for d in techlog:
kind = d["kind"]
if kind == "Namespace":
labels = d["metadata"].get("labels", {})
want = {
"pod-security.kubernetes.io/enforce": "baseline",
"pod-security.kubernetes.io/warn": "restricted",
"pod-security.kubernetes.io/audit": "restricted",
"observability.hyeonworks.com/enabled": "true",
}
for k, v in want.items():
if labels.get(k) != v:
errors.append(f"hyeonworks-prod label {k} must be {v}")
if kind == "DatabaseRole":
spec = d["spec"]
if spec.get("passwordSecret", {}).get("name") != "techlog-db-credentials":
errors.append("techlog DatabaseRole must reference techlog-db-credentials")
for flag in ("superuser", "createdb", "createrole", "replication", "bypassrls"):
if spec.get(flag) is not False:
errors.append(f"techlog DatabaseRole {flag} must be false")
if kind in ("Database", "DatabaseRole"):
policy = d["spec"].get("databaseReclaimPolicy") or d["spec"].get("databaseRoleReclaimPolicy")
if policy != "retain":
errors.append(f"{kind} must keep the retain reclaim policy")
if kind == "ConfigMap":
labels = d["metadata"].get("labels", {})
if labels.get("grafana_dashboard") != "1":
errors.append("tech-log dashboard ConfigMap needs grafana_dashboard=1")
if d["metadata"]["name"] != "grafana-dashboard-techlog":
errors.append("tech-log dashboard ConfigMap must keep its name (no hash suffix)")
classes = {d["metadata"]["name"]: d for d in load("priority-classes.yaml")}
if sorted(classes) != ["platform-critical", "platform-low"]:
errors.append(f"PriorityClasses differ: {sorted(classes)}")
else:
crit, low = classes["platform-critical"], classes["platform-low"]
if not (0 < crit["value"] < 1_000_000_000):
errors.append("platform-critical must be above 0 and below the system classes")
if not low["value"] < 0:
errors.append("platform-low must be below the default priority 0")
if low.get("preemptionPolicy") != "Never":
errors.append("platform-low must never preempt")
for d in classes.values():
if d.get("globalDefault") is not False:
errors.append(f"{d['metadata']['name']} must not be the global default")
policies = {d["metadata"]["name"]: d for d in load("keycloak-network-policies.yaml")}
deny = policies.get("keycloak-default-deny")
if not deny or deny["spec"].get("podSelector") != {} or sorted(deny["spec"].get("policyTypes", [])) != ["Egress", "Ingress"]:
errors.append("keycloak needs a namespace-wide default deny for ingress and egress")
for d in policies.values():
if d["metadata"].get("namespace") != "keycloak":
errors.append(f"{d['metadata']['name']} must live in the keycloak namespace")
for rule in d["spec"].get("egress", []) or []:
for peer in rule.get("to", []):
cidr = peer.get("ipBlock", {}).get("cidr")
if cidr and cidr not in ("10.43.0.1/32", "192.168.0.107/32"):
errors.append(f"{d['metadata']['name']}: unexpected egress CIDR {cidr}")
if not rule.get("ports"):
errors.append(f"{d['metadata']['name']}: every egress rule must name its ports")
if errors:
for e in errors:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
print(f"tech-log tenant: {len(techlog)} objects; PriorityClasses: {len(classes)}; keycloak NetworkPolicies: {len(policies)}")
PY
echo "TENANTS AND POLICIES STATIC RENDER PASS"