Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions k8s/llm/portkey/networkpolicy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 0 additions & 3 deletions k8s/otel/networkpolicy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-10-26
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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`
Original file line number Diff line number Diff line change
@@ -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).
31 changes: 31 additions & 0 deletions openspec/specs/k8s-network-policies/spec.md
Original file line number Diff line number Diff line change
@@ -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`
53 changes: 53 additions & 0 deletions tests/test_k8s_network_policies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 == []
Loading