From 5017f2bc600898ae4d034281fcaf7f5179497a6c Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 15:30:47 +0000 Subject: [PATCH] fix(k8s): network policy peers name only namespaces that exist (#1656) Remove the nonexistent devops-cli namespace peer from the Portkey perimeter NetworkPolicy and the nonexistent ingress namespace peer from the OpenTelemetry perimeter NetworkPolicy. Add an automated invariant test asserting that every namespaceSelector in Kubernetes NetworkPolicies names a declared or built-in namespace. Closes #1656 Change: `openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/` --- k8s/llm/portkey/networkpolicy.yaml | 5 +- k8s/otel/networkpolicy.yaml | 3 -- .../.openspec.yaml | 2 + .../design.md | 38 +++++++++++++ .../proposal.md | 47 ++++++++++++++++ .../specs/k8s-network-policies/spec.md | 32 +++++++++++ .../tasks.md | 12 +++++ openspec/specs/k8s-network-policies/spec.md | 31 +++++++++++ tests/test_k8s_network_policies.py | 53 +++++++++++++++++++ 9 files changed, 216 insertions(+), 7 deletions(-) create mode 100644 openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/.openspec.yaml create mode 100644 openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/design.md create mode 100644 openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/proposal.md create mode 100644 openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/specs/k8s-network-policies/spec.md create mode 100644 openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/tasks.md create mode 100644 openspec/specs/k8s-network-policies/spec.md diff --git a/k8s/llm/portkey/networkpolicy.yaml b/k8s/llm/portkey/networkpolicy.yaml index a39b66b95c..aabe78be40 100644 --- a/k8s/llm/portkey/networkpolicy.yaml +++ b/k8s/llm/portkey/networkpolicy.yaml @@ -16,11 +16,8 @@ spec: - Ingress - Egress ingress: - # Allow incoming API requests to port 8787 from devops-cli stack workloads and monitoring + # Allow incoming API requests to port 8787 from stack workloads and monitoring - from: - - namespaceSelector: - matchLabels: - kubernetes.io/metadata.name: devops-cli - podSelector: matchLabels: app.kubernetes.io/part-of: devops-cli-stack diff --git a/k8s/otel/networkpolicy.yaml b/k8s/otel/networkpolicy.yaml index d82b87a83c..f76343b22e 100644 --- a/k8s/otel/networkpolicy.yaml +++ b/k8s/otel/networkpolicy.yaml @@ -19,9 +19,6 @@ spec: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: monitoring - - namespaceSelector: - matchLabels: - kubernetes.io/metadata.name: ingress - namespaceSelector: matchLabels: kubernetes.io/metadata.name: kube-system diff --git a/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/.openspec.yaml b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/.openspec.yaml new file mode 100644 index 0000000000..d58ba02327 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-26 diff --git a/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/design.md b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/design.md new file mode 100644 index 0000000000..07ff72ca9f --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/design.md @@ -0,0 +1,38 @@ +# Design + +## Context + +See `proposal.md` for motivation. +Kubernetes NetworkPolicies restrict network traffic through pod and namespace selectors. +In `k8s/llm/portkey/networkpolicy.yaml`, an ingress peer targets `kubernetes.io/metadata.name: devops-cli`. +In `k8s/otel/networkpolicy.yaml`, an ingress peer targets `kubernetes.io/metadata.name: ingress`. +Neither namespace exists in `k8s/namespaces.yaml` nor in the cluster runtime. + +## Goals / Non-Goals + +**Goals:** +- Remove the nonexistent `devops-cli` peer from `k8s/llm/portkey/networkpolicy.yaml`. +- Update the comment in `k8s/llm/portkey/networkpolicy.yaml` to match active peers. +- Remove the nonexistent `ingress` peer from `k8s/otel/networkpolicy.yaml`. +- Add an automated invariant test in `tests/test_k8s_network_policies.py` that verifies every `namespaceSelector` matches a declared or built-in namespace. + +**Non-Goals:** +- Adding a new `devops-cli` or `ingress` namespace to `k8s/namespaces.yaml`. +- Changing egress rules or routes for Portkey or OpenTelemetry. + +## Decisions + +### Decision 1: Remove nonexistent namespace peers instead of creating dummy namespaces +- Rationale: Creating empty namespaces adds resource clutter and misleads maintainers. Portkey receives calls from stack workloads in `llm` and monitoring; OpenTelemetry Tempo receives ingress through Traefik in `kube-system` and monitoring. Neither requires `devops-cli` or `ingress`. +- Rejected Alternative: Adding `devops-cli` and `ingress` namespaces to `k8s/namespaces.yaml`. + - Evidence: The cluster stack namespace is `devops`, not `devops-cli`. Ingress routing runs via Traefik in `kube-system`. Adding empty namespaces violates the principle of minimal resource footprint and preserves vestigial configuration. + +### Decision 2: Add an offline invariant test in `tests/test_k8s_network_policies.py` +- Rationale: The repository tests Kubernetes manifests offline with `pyyaml`. The test loads `k8s/namespaces.yaml`, determines valid namespaces plus built-in namespaces (`kube-system`, `default`), scans all YAML manifests in `k8s/` for `namespaceSelector` blocks, and asserts that every `kubernetes.io/metadata.name` matches a valid namespace. +- Rejected Alternative: Running live cluster validation with `kubectl` or Kyverno CLI during test execution. + - Evidence: AGENTS.md and `docs/TESTING.md` require tests to double external edges and run hermetically offline. Pytest file scanning runs in milliseconds without requiring cluster access or binary dependencies. + +## Risks / Trade-offs + +- [Risk] A future legitimate namespace is added but fails the test. + → Mitigation: The test reads `k8s/namespaces.yaml` dynamically, so adding the namespace to `k8s/namespaces.yaml` automatically satisfies the test. diff --git a/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/proposal.md b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/proposal.md new file mode 100644 index 0000000000..1eb613c995 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/proposal.md @@ -0,0 +1,47 @@ +# Proposal + +## Why + +Two Kubernetes NetworkPolicies admit traffic from namespaces that do not exist (#1656). +NetworkPolicy `portkey-perimeter` admits traffic from namespace `devops-cli`, but the stack namespace is `devops`. +NetworkPolicy `otel-default-perimeter` admits traffic from namespace `ingress`, but Traefik runs in `kube-system`. +Correcting these peers aligns policy definitions with declared cluster namespaces and prevents misleading configurations. + +This change fits in one pull request. + +## What Changes + +Manifests are observable cluster definitions and define access control rules: +- Remove the nonexistent `devops-cli` namespaceSelector peer from `k8s/llm/portkey/networkpolicy.yaml`. +- Update the comment in `k8s/llm/portkey/networkpolicy.yaml` to reflect admission from stack workloads and monitoring. +- Remove the nonexistent `ingress` namespaceSelector peer from `k8s/otel/networkpolicy.yaml`. +- Add an automated invariant test asserting that every `kubernetes.io/metadata.name` in all `namespaceSelector` blocks under `k8s/` resolves to a declared namespace in `k8s/namespaces.yaml` or a built-in namespace (`kube-system`, `default`). + +## Capabilities + +### New Capabilities +- `k8s-network-policies`: Namespace selector validation and isolation rules for Kubernetes network policies. + +### Modified Capabilities + +## Impact + +- Manifest changes: `k8s/llm/portkey/networkpolicy.yaml` and `k8s/otel/networkpolicy.yaml`. +- Test suite: `tests/test_k8s_network_policies.py` gains invariant coverage for namespace references in network policies. +- No runtime impact on cluster traffic because the removed peers did not match any running pods. + +## Feasibility + +We confirmed the premise by inspecting cluster manifest files and verifying against live namespace inventory: +- `k8s/namespaces.yaml` declares namespaces `argocd`, `monitoring`, `otel`, `llm`, `logging`, `cloudflared`, `devops`, `agents`, `argo-workflows`, and `gitea`. +- Neither `devops-cli` nor `ingress` exists as a declared namespace. +- Live inspection confirmed that Traefik runs in `kube-system` and stack workloads run in `devops` or `llm`. +- Upstream Kubernetes documentation confirms that `namespaceSelector` matches labels on `Namespace` resources; references to nonexistent namespaces match zero pods. + +## Existing Tool Considered + +We considered `kubeconform` and standard Kubernetes JSON schema validation. +Schema validation verifies resource syntax, but it does not validate cross-resource references such as namespace names in selectors. +We also considered writing a custom Open Policy Agent (OPA) Gatekeeper or Kyverno policy. +Adding an external admission controller policy requires running an admission webhook engine during CI, whereas an offline pytest invariant verifies the manifests with zero extra dependencies and sub-second execution. +Therefore, a focused offline pytest invariant in `tests/test_k8s_network_policies.py` satisfies the invariant check requirement with no added runtime complexity. diff --git a/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/specs/k8s-network-policies/spec.md b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/specs/k8s-network-policies/spec.md new file mode 100644 index 0000000000..b3f0fcb7b0 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/specs/k8s-network-policies/spec.md @@ -0,0 +1,32 @@ +# Spec Delta + +## Purpose + +Provides namespace selector validation and isolation invariants for Kubernetes NetworkPolicies. + +## ADDED Requirements + +### Requirement: Network policy namespace selectors reference declared or built-in namespaces +Every `kubernetes.io/metadata.name` label selector declared under `namespaceSelector` in Kubernetes NetworkPolicies SHALL reference a namespace declared in `k8s/namespaces.yaml` or a standard built-in namespace (`kube-system`, `default`). + +#### Scenario: Valid namespace selectors +- **WHEN** the test suite audits all `namespaceSelector` blocks in Kubernetes NetworkPolicies +- **THEN** every referenced namespace exists in `k8s/namespaces.yaml` or matches `kube-system` or `default` + +#### Scenario: Unmatched namespace selector detected +- **WHEN** a NetworkPolicy includes a `namespaceSelector` matching an undeclared namespace +- **THEN** the manifest validation check fails and identifies the offending file and namespace + +### Requirement: Portkey perimeter admits traffic from stack workloads and monitoring only +The Portkey perimeter NetworkPolicy (`k8s/llm/portkey/networkpolicy.yaml`) SHALL restrict ingress traffic on port 8787 to pods labeled `app.kubernetes.io/part-of: devops-cli-stack` and the `monitoring` namespace. + +#### Scenario: Portkey perimeter ingress peers +- **WHEN** inspecting the ingress configuration of `portkey-perimeter` +- **THEN** ingress admits only `devops-cli-stack` pods and namespace `monitoring` on TCP port 8787 + +### Requirement: OpenTelemetry perimeter ingress admits monitoring and Traefik in kube-system +The OpenTelemetry default perimeter NetworkPolicy (`k8s/otel/networkpolicy.yaml`) SHALL admit ingress to port 3200 from the `monitoring` namespace and from Traefik pods in the `kube-system` namespace. + +#### Scenario: OpenTelemetry perimeter ingress peers +- **WHEN** inspecting the ingress rule for port 3200 of `otel-default-perimeter` +- **THEN** ingress admits only namespace `monitoring` and Traefik pods in namespace `kube-system` diff --git a/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/tasks.md b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/tasks.md new file mode 100644 index 0000000000..b87df02e6a --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1656-network-policy-namespaces/tasks.md @@ -0,0 +1,12 @@ +# Tasks + +## 1. NetworkPolicy namespace peer correction + +- [x] 1.1 Add failing invariant test in `tests/test_k8s_network_policies.py` asserting that every `namespaceSelector` under `k8s/` names a declared or built-in namespace, and verify with `uv run devops ci test tests/test_k8s_network_policies.py`. +- [x] 1.2 Remove the `devops-cli` peer and update the comment in `k8s/llm/portkey/networkpolicy.yaml`, and verify with `uv run devops ci test tests/test_k8s_network_policies.py`. +- [x] 1.3 Remove the `ingress` peer from `k8s/otel/networkpolicy.yaml`, and verify with `uv run devops ci test tests/test_k8s_network_policies.py`. +- [x] 1.4 Run documentation synchronization with `uv run devops docs generate --sync-readme`. + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). diff --git a/openspec/specs/k8s-network-policies/spec.md b/openspec/specs/k8s-network-policies/spec.md new file mode 100644 index 0000000000..505a789261 --- /dev/null +++ b/openspec/specs/k8s-network-policies/spec.md @@ -0,0 +1,31 @@ +# k8s-network-policies Specification + +## Purpose +Provides namespace selector validation and isolation invariants for Kubernetes NetworkPolicies. + +## Requirements + +### Requirement: Network policy namespace selectors reference declared or built-in namespaces +Every `kubernetes.io/metadata.name` label selector declared under `namespaceSelector` in Kubernetes NetworkPolicies SHALL reference a namespace declared in `k8s/namespaces.yaml` or a standard built-in namespace (`kube-system`, `default`). + +#### Scenario: Valid namespace selectors +- **WHEN** the test suite audits all `namespaceSelector` blocks in Kubernetes NetworkPolicies +- **THEN** every referenced namespace exists in `k8s/namespaces.yaml` or matches `kube-system` or `default` + +#### Scenario: Unmatched namespace selector detected +- **WHEN** a NetworkPolicy includes a `namespaceSelector` matching an undeclared namespace +- **THEN** the manifest validation check fails and identifies the offending file and namespace + +### Requirement: Portkey perimeter admits traffic from stack workloads and monitoring only +The Portkey perimeter NetworkPolicy (`k8s/llm/portkey/networkpolicy.yaml`) SHALL restrict ingress traffic on port 8787 to pods labeled `app.kubernetes.io/part-of: devops-cli-stack` and the `monitoring` namespace. + +#### Scenario: Portkey perimeter ingress peers +- **WHEN** inspecting the ingress configuration of `portkey-perimeter` +- **THEN** ingress admits only `devops-cli-stack` pods and namespace `monitoring` on TCP port 8787 + +### Requirement: OpenTelemetry perimeter ingress admits monitoring and Traefik in kube-system +The OpenTelemetry default perimeter NetworkPolicy (`k8s/otel/networkpolicy.yaml`) SHALL admit ingress to port 3200 from the `monitoring` namespace and from Traefik pods in the `kube-system` namespace. + +#### Scenario: OpenTelemetry perimeter ingress peers +- **WHEN** inspecting the ingress rule for port 3200 of `otel-default-perimeter` +- **THEN** ingress admits only namespace `monitoring` and Traefik pods in namespace `kube-system` diff --git a/tests/test_k8s_network_policies.py b/tests/test_k8s_network_policies.py index 50085bd453..34bcc573af 100644 --- a/tests/test_k8s_network_policies.py +++ b/tests/test_k8s_network_policies.py @@ -463,3 +463,56 @@ def test_loki_otel_peer_names_the_collector_release_the_stack_installs() -> None None, labels["app.kubernetes.io/name"], ) + + +def _extract_metadata_names(selector: dict[str, Any]) -> list[str]: + names: list[str] = [] + match_labels = selector.get("matchLabels", {}) + if isinstance(match_labels, dict) and "kubernetes.io/metadata.name" in match_labels: + names.append(match_labels["kubernetes.io/metadata.name"]) + for expr in selector.get("matchExpressions", []): + if isinstance(expr, dict) and expr.get("key") == "kubernetes.io/metadata.name": + names.extend(expr.get("values", [])) + return names + + +def _extract_namespace_selectors(data: Any) -> list[str]: + """Recursively find all kubernetes.io/metadata.name values inside namespaceSelector objects.""" + names: list[str] = [] + if isinstance(data, dict): + for k, v in data.items(): + if k == "namespaceSelector" and isinstance(v, dict): + names.extend(_extract_metadata_names(v)) + else: + names.extend(_extract_namespace_selectors(v)) + elif isinstance(data, list): + for item in data: + names.extend(_extract_namespace_selectors(item)) + return names + + +def test_every_network_policy_namespace_selector_names_a_declared_or_builtin_namespace() -> None: + """Verify every kubernetes.io/metadata.name in a namespaceSelector under k8s/ names a declared or built-in namespace (#1656). + + A selector that names a namespace that does not exist matches zero pods and states an + intent that the policy does not enforce. + """ + declared = { + doc["metadata"]["name"] + for doc in yaml.safe_load_all((K8S_DIR / "namespaces.yaml").read_text(encoding="utf-8")) + if isinstance(doc, dict) and doc.get("kind") == "Namespace" + } + allowed = declared | {"kube-system", "default"} + + violations: list[tuple[str, str]] = [] + for path in sorted(K8S_DIR.rglob("*.y*ml")): + try: + docs = list(yaml.safe_load_all(path.read_text(encoding="utf-8"))) + except Exception: + continue + for doc in docs: + for namespace in _extract_namespace_selectors(doc): + if namespace not in allowed: + violations.append((str(path.relative_to(K8S_DIR)), namespace)) + + assert violations == []