Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

test(np-08): harden local authorization gates

Alfredo Lopezcbb77390d791
diff --git a/scripts/e2e/e2e-np08-hcc-authorization.sh b/scripts/e2e/e2e-np08-hcc-authorization.sh
index ada5195dc..bfb0b3dca 100755
--- a/scripts/e2e/e2e-np08-hcc-authorization.sh
+++ b/scripts/e2e/e2e-np08-hcc-authorization.sh
@@ -18,6 +18,9 @@ usage: scripts/e2e/e2e-np08-hcc-authorization.sh --context <branch-owned-minikub
USAGE
}
+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
+PROJECT_DIR="$(cd -- "${SCRIPT_DIR}/../.." && pwd -P)"
+
context=''
while [[ $# -gt 0 ]]; do
case "$1" in
@@ -41,6 +44,12 @@ if [[ -z "${context}" ]]; then
exit 2
fi
+profile="${MINIKUBE_PROFILE:-${context}}"
+if [[ "${profile}" != "${context}" ]]; then
+ echo "FAIL: MINIKUBE_PROFILE must equal --context for the deployed NP-08 gate" >&2
+ exit 2
+fi
+
case "${context}" in
clerum-codex-np-08-cross-context-mcp-token-plan-*) ;;
*)
@@ -49,7 +58,7 @@ case "${context}" in
;;
esac
-for command_name in kubectl jq; do
+for command_name in kubectl jq git shasum awk python3; do
command -v "${command_name}" >/dev/null || {
echo "FAIL: required command missing: ${command_name}" >&2
exit 1
@@ -60,28 +69,120 @@ kctl() {
kubectl --context="${context}" "$@"
}
+SYNC_CONFIGMAP="${CLERUM_PRE_GATE_SYNC_CONFIGMAP:-clerum-pre-gate-sync-state}"
+PORTS_ENV="${CLERUM_PROFILE_PORTS_ENV:-${HOME}/.cache/clerum/minikube-profiles/${profile}/ports.env}"
+
+verify_profile_ownership() {
+ [[ -f "${PORTS_ENV}" ]] || {
+ echo "FAIL: branch profile ports.env is missing: ${PORTS_ENV}" >&2
+ exit 1
+ }
+ local profile_dir profile_name profile_repo profile_dirty
+ profile_dir="${PORTS_ENV%/ports.env}"
+ profile_name="$(awk -F= '$1 == "PROFILE" { print substr($0, index($0, "=") + 1); exit }' "${profile_dir}/profile.env" 2>/dev/null || true)"
+ profile_repo="$(awk -F= '$1 == "REPO_DIR" { print substr($0, index($0, "=") + 1); exit }' "${profile_dir}/profile.env" 2>/dev/null || true)"
+ profile_dirty="$(awk -F= '$1 == "DIRTY" { print substr($0, index($0, "=") + 1); exit }' "${profile_dir}/profile.env" 2>/dev/null || true)"
+ [[ "${profile_name}" == "${profile}" ]] || {
+ echo "FAIL: profile marker belongs to '${profile_name:-unknown}', not ${profile}" >&2
+ exit 1
+ }
+ [[ "${profile_dirty}" == "false" ]] || {
+ echo "FAIL: profile marker is dirty; refuse stale-profile E2E" >&2
+ exit 1
+ }
+ [[ -n "${profile_repo}" && "$(cd -- "${profile_repo}" 2>/dev/null && pwd -P)" == "${PROJECT_DIR}" ]] || {
+ echo "FAIL: profile marker belongs to another worktree: ${profile_repo:-unknown}" >&2
+ exit 1
+ }
+}
+
+verify_clean_and_sync_marker() {
+ local head worktree_id marker_json
+ [[ -z "$(git -C "${PROJECT_DIR}" status --porcelain)" ]] || {
+ echo "FAIL: worktree is dirty; commit or restore before deployed NP-08 E2E" >&2
+ exit 1
+ }
+ head="$(git -C "${PROJECT_DIR}" rev-parse --verify HEAD)"
+ worktree_id="$(printf '%s' "${PROJECT_DIR}" | shasum | awk '{print $1}')"
+ marker_json="$(kctl -n control-plane get configmap "${SYNC_CONFIGMAP}" -o json 2>/dev/null)" || {
+ echo "FAIL: pre-gate marker is missing: control-plane/${SYNC_CONFIGMAP}" >&2
+ exit 1
+ }
+ python3 - "${worktree_id}" "${head}" "${marker_json}" <<'PY'
+import json
+import sys
+
+expected_worktree, expected_head, marker_json = sys.argv[1:]
+data = (json.loads(marker_json).get("data") or {})
+if not data.get("clusterFingerprint"):
+ raise SystemExit("FAIL: pre-gate marker has no cluster fingerprint")
+if data.get("worktreeId") != expected_worktree:
+ raise SystemExit("FAIL: pre-gate marker belongs to another worktree")
+if data.get("gitHead") != expected_head:
+ raise SystemExit("FAIL: pre-gate marker does not match current HEAD")
+if data.get("imageSource") != "local":
+ raise SystemExit("FAIL: pre-gate marker is not for local images")
+PY
+}
+
MCP_NS='mcp-server'
HOST_NS='mcp-host'
CONTROL_NS='control-plane'
HOST_DEPLOYMENT='chatllm'
+RUN_ID="${NP08_E2E_RUN_ID:-$(date -u +%Y%m%d%H%M%S)-$$}"
+OWNER_LABEL_KEY='np08.evenfire/owner'
+OWNER_LABEL_VALUE='hcc-authorization'
CONTEXT_A='context1'
-CONTEXT_B='np08-e2e-context-b'
-SERVER_A='np08-e2e-server-a'
-SERVER_B='np08-e2e-server-b'
-SECRET_A='np08-e2e-server-a-auth'
-SECRET_B='np08-e2e-server-b-auth'
+CONTEXT_B="np08-e2e-${RUN_ID}-context-b"
+SERVER_A="np08-e2e-${RUN_ID}-server-a"
+SERVER_B="np08-e2e-${RUN_ID}-server-b"
+SECRET_A="np08-e2e-${RUN_ID}-server-a-auth"
+SECRET_B="np08-e2e-${RUN_ID}-server-b-auth"
+
+verify_profile_ownership
+verify_clean_and_sync_marker
cleanup() {
local status=$?
+ local cleanup_status=0
+ local remove_patch residual context_contains_fixture context_a_json
set +e
- if [[ -n "${original_servers:-}" ]]; then
- local restore_patch
- restore_patch="$(jq -cn --argjson servers "${original_servers}" '{spec:{mcpServers:$servers}}')"
- kctl -n "${MCP_NS}" patch context "${CONTEXT_A}" --type=merge -p "${restore_patch}" >/dev/null 2>&1
+ if [[ "${fixture_context_patched:-0}" == 1 ]]; then
+ remove_patch="$(kctl -n "${MCP_NS}" get context "${CONTEXT_A}" -o json 2>/dev/null | jq -c --arg server "${SERVER_A}" '
+ [(.spec.mcpServers // [] | to_entries[] | select(.value == $server) | .key)]
+ | reverse | map({op:"remove", path:("/spec/mcpServers/" + tostring)})' 2>/dev/null)"
+ if [[ -z "${remove_patch}" || "${remove_patch}" == "null" ]]; then
+ cleanup_status=1
+ elif [[ "${remove_patch}" != '[]' ]] && ! kctl -n "${MCP_NS}" patch context "${CONTEXT_A}" --type=json -p "${remove_patch}" >/dev/null 2>&1; then
+ cleanup_status=1
+ fi
+ fi
+ for resource in mcpserver secret context; do
+ if ! kctl -n "${MCP_NS}" delete "${resource}" \
+ -l "${OWNER_LABEL_KEY}=${OWNER_LABEL_VALUE},np08.evenfire/run=${RUN_ID}" \
+ --ignore-not-found >/dev/null 2>&1; then
+ cleanup_status=1
+ fi
+ done
+ context_a_json="$(kctl -n "${MCP_NS}" get context "${CONTEXT_A}" -o json 2>/dev/null)" || cleanup_status=1
+ if [[ -n "${context_a_json}" ]]; then
+ context_contains_fixture="$(jq -r --arg server "${SERVER_A}" '(.spec.mcpServers // []) | any(. == $server)' <<<"${context_a_json}" 2>/dev/null)" || cleanup_status=1
+ else
+ context_contains_fixture='unknown'
+ fi
+ if [[ "${context_contains_fixture}" == "true" ]]; then
+ cleanup_status=1
+ fi
+ for resource in mcpserver secret context; do
+ residual="$(kctl -n "${MCP_NS}" get "${resource}" -l "${OWNER_LABEL_KEY}=${OWNER_LABEL_VALUE},np08.evenfire/run=${RUN_ID}" -o name 2>/dev/null)"
+ if [[ -n "${residual}" ]]; then
+ cleanup_status=1
+ fi
+ done
+ if [[ "${cleanup_status}" -ne 0 ]]; then
+ status=1
+ echo 'FAIL: NP-08 E2E cleanup did not remove all owned fixtures' >&2
fi
- kctl -n "${MCP_NS}" delete mcpserver "${SERVER_A}" "${SERVER_B}" --ignore-not-found >/dev/null 2>&1
- kctl -n "${MCP_NS}" delete context "${CONTEXT_B}" --ignore-not-found >/dev/null 2>&1
- kctl -n "${MCP_NS}" delete secret "${SECRET_A}" "${SECRET_B}" --ignore-not-found >/dev/null 2>&1
if [[ "${status}" -eq 0 ]]; then
echo 'PASS: NP-08 deployed HCC authorization E2E'
else
@@ -100,7 +201,10 @@ kctl -n "${CONTROL_NS}" get deployment host-context-controller-api-gateway \
kctl -n "${HOST_NS}" get deployment "${HOST_DEPLOYMENT}" \
-o jsonpath='{.status.readyReplicas}' | grep -qx '1'
-original_servers="$(kctl -n "${MCP_NS}" get context "${CONTEXT_A}" -o json | jq -c '.spec.mcpServers // []')"
+if kctl -n "${MCP_NS}" get context "${CONTEXT_A}" -o json | jq -e --arg server "${SERVER_A}" '(.spec.mcpServers // []) | any(. == $server)' >/dev/null; then
+ echo "FAIL: generated fixture server name already exists in ${CONTEXT_A}" >&2
+ exit 1
+fi
# The fixtures are deliberately managed:false: HCC must expose their live
# authority state without creating a workload or opening a new transport lane.
@@ -110,24 +214,33 @@ kind: Secret
metadata:
name: ${SECRET_A}
namespace: ${MCP_NS}
+ labels:
+ ${OWNER_LABEL_KEY}: ${OWNER_LABEL_VALUE}
+ np08.evenfire/run: ${RUN_ID}
type: Opaque
stringData:
- token: np08-synthetic-a
+ token: np08-synthetic-${RUN_ID}-a
---
apiVersion: v1
kind: Secret
metadata:
name: ${SECRET_B}
namespace: ${MCP_NS}
+ labels:
+ ${OWNER_LABEL_KEY}: ${OWNER_LABEL_VALUE}
+ np08.evenfire/run: ${RUN_ID}
type: Opaque
stringData:
- token: np08-synthetic-b
+ token: np08-synthetic-${RUN_ID}-b
---
apiVersion: clerum.io/v1alpha1
kind: Context
metadata:
name: ${CONTEXT_B}
namespace: ${MCP_NS}
+ labels:
+ ${OWNER_LABEL_KEY}: ${OWNER_LABEL_VALUE}
+ np08.evenfire/run: ${RUN_ID}
spec:
contextId: ${CONTEXT_B}
mcpServers:
@@ -138,6 +251,9 @@ kind: McpServer
metadata:
name: ${SERVER_A}
namespace: ${MCP_NS}
+ labels:
+ ${OWNER_LABEL_KEY}: ${OWNER_LABEL_VALUE}
+ np08.evenfire/run: ${RUN_ID}
spec:
contextRef: ${CONTEXT_A}
image: clerum/mock-mcp-server:dev
@@ -157,6 +273,9 @@ kind: McpServer
metadata:
name: ${SERVER_B}
namespace: ${MCP_NS}
+ labels:
+ ${OWNER_LABEL_KEY}: ${OWNER_LABEL_VALUE}
+ np08.evenfire/run: ${RUN_ID}
spec:
contextRef: ${CONTEXT_B}
image: clerum/mock-mcp-server:dev
@@ -172,25 +291,28 @@ spec:
enabled: true
YAML
-# Append only the fixture owned by this test, preserving the original Context
-# allowlist for cleanup and for any concurrently seeded local E2E data.
+# Append only the fixture owned by this test; cleanup removes only this
+# test's matching server entry and labeled resources.
kctl -n "${MCP_NS}" patch context "${CONTEXT_A}" --type=json \
-p="[{\"op\":\"add\",\"path\":\"/spec/mcpServers/-\",\"value\":\"${SERVER_A}\"}]" >/dev/null
+fixture_context_patched=1
echo 'E2E setup: waiting for HCC to observe the synthetic Context/McpServer fixtures'
# Keep the runtime JWT and the returned synthetic token inside the Host pod.
# The process emits only assertion labels and status/error classes.
-kctl -n "${HOST_NS}" exec -i "deploy/${HOST_DEPLOYMENT}" -- node - <<'NODE'
+kctl -n "${HOST_NS}" exec -i "deploy/${HOST_DEPLOYMENT}" -- \
+ env "NP08_SERVER_A=${SERVER_A}" "NP08_SERVER_B=${SERVER_B}" \
+ "NP08_EXPECTED_SYNTHETIC_TOKEN=np08-synthetic-${RUN_ID}-a" node - <<'NODE'
const base = 'http://host-context-controller-api-gateway.control-plane.svc.cluster.local:8081'
let accessToken = process.env.MCP_HOST_RUNTIME_ACCESS_TOKEN
const refreshToken = process.env.MCP_HOST_RUNTIME_REFRESH_TOKEN
const workflowToken = process.env.MCP_HOST_WORKFLOW_CONTROL_TOKEN
-const serverA = 'np08-e2e-server-a'
-const serverB = 'np08-e2e-server-b'
-const expectedSyntheticToken = 'np08-synthetic-a'
+const serverA = process.env.NP08_SERVER_A
+const serverB = process.env.NP08_SERVER_B
+const expectedSyntheticToken = process.env.NP08_EXPECTED_SYNTHETIC_TOKEN
-if (!accessToken || !refreshToken || !workflowToken) {
+if (!accessToken || !refreshToken || !workflowToken || !serverA || !serverB || !expectedSyntheticToken) {
throw new Error('runtime token environment is unavailable')
}
@@ -258,7 +380,7 @@ await assertEventually('same-Context inventory', async () => {
if (!Array.isArray(body?.servers)) return false
const names = body.servers.map(server => server?.name)
if (!names.includes(serverA) || names.includes(serverB)) return false
- if (JSON.stringify(body).includes('secretRef') || JSON.stringify(body).includes('np08-synthetic-a')) {
+ if (JSON.stringify(body).includes('secretRef') || JSON.stringify(body).includes(expectedSyntheticToken)) {
throw new Error('inventory exposed credential material')
}
return true
diff --git a/scripts/security/check-np08-mcp-host-networkpolicy.rb b/scripts/security/check-np08-mcp-host-networkpolicy.rb
index 3091e023a..30c6c25f9 100755
--- a/scripts/security/check-np08-mcp-host-networkpolicy.rb
+++ b/scripts/security/check-np08-mcp-host-networkpolicy.rb
@@ -28,6 +28,11 @@ PUBLIC_EGRESS_EXCEPTIONS = %w[
].freeze
documents = JSON.parse(STDIN.read)
+host_pods = nil
+if ARGV[0] == "--host-pods"
+ pods_path = ARGV.fetch(1)
+ host_pods = JSON.parse(File.read(pods_path))
+end
policies = Array(documents.fetch("items", [])).select do |document|
document.is_a?(Hash) &&
document["kind"] == "NetworkPolicy" &&
@@ -38,6 +43,81 @@ policy_rules = policies.flat_map do |policy|
Array(policy.dig("spec", "egress")).map { |rule| [policy, rule] }
end
+selector_matches = lambda do |selector, labels|
+ selector = {} if selector.nil?
+ next false unless selector.is_a?(Hash) && labels.is_a?(Hash)
+
+ match_labels = selector["matchLabels"]
+ next false unless !match_labels || (match_labels.is_a?(Hash) && match_labels.all? { |key, value| labels[key] == value })
+
+ Array(selector["matchExpressions"]).all? do |expression|
+ next false unless expression.is_a?(Hash)
+
+ key = expression["key"]
+ operator = expression["operator"]
+ values = Array(expression["values"])
+ case operator
+ when "In"
+ values.include?(labels[key])
+ when "NotIn"
+ !values.include?(labels[key])
+ when "Exists"
+ labels.key?(key)
+ when "DoesNotExist"
+ !labels.key?(key)
+ else
+ false
+ end
+ end
+end
+
+policy_types_include_egress = lambda do |policy|
+ Array(policy.dig("spec", "policyTypes")).include?("Egress")
+end
+
+exact_pod_selector = lambda do |policy, expected_labels|
+ selector = policy.dig("spec", "podSelector")
+ selector.is_a?(Hash) && selector.keys.sort == ["matchLabels"] &&
+ selector["matchLabels"] == expected_labels && Array(selector["matchExpressions"]).empty?
+end
+
+default_deny = policies.find { |policy| policy.dig("metadata", "name") == "deny-all-mcp-host" }
+managed_host_policy = policies.find { |policy| policy.dig("metadata", "name") == "mcp-host" }
+context_allow_policies = policies.select do |policy|
+ policy.dig("metadata", "labels", "clerum.io/policy-type") == "context-allow"
+end
+
+selector_contract_ok =
+ default_deny.is_a?(Hash) &&
+ default_deny.dig("spec", "podSelector") == {} &&
+ policy_types_include_egress.call(default_deny) &&
+ managed_host_policy.is_a?(Hash) &&
+ exact_pod_selector.call(managed_host_policy, { "clerum.io/managed-by" => "host-context-controller" }) &&
+ policy_types_include_egress.call(managed_host_policy) &&
+ context_allow_policies.all? do |policy|
+ labels = policy.dig("spec", "podSelector", "matchLabels")
+ context = policy.dig("metadata", "labels", "clerum.io/context")
+ labels.is_a?(Hash) &&
+ labels["clerum.io/managed-by"] == "host-context-controller" &&
+ labels["clerum.io/context"] == context &&
+ Array(policy.dig("spec", "podSelector", "matchExpressions")).empty? &&
+ policy_types_include_egress.call(policy)
+ end
+
+if host_pods
+ managed_host_pods = Array(host_pods.fetch("items", [])).select do |pod|
+ pod.dig("metadata", "labels", "clerum.io/managed-by") == "host-context-controller"
+ end
+ selector_contract_ok &&= !managed_host_pods.empty? && managed_host_pods.all? do |pod|
+ labels = pod.dig("metadata", "labels") || {}
+ policies.any? do |policy|
+ policy_types_include_egress.call(policy) &&
+ !Array(policy.dig("spec", "egress")).empty? &&
+ selector_matches.call(policy.dig("spec", "podSelector"), labels)
+ end
+ end
+end
+
port_is_numeric = lambda do |port|
port.is_a?(Hash) &&
port["port"].is_a?(Integer) &&
@@ -175,7 +255,10 @@ end
egress_contract_ok &&= gfs_contract_ok
hcc_lane = policy_rules.any? do |_policy, rule|
- allows_tcp_port.call(rule, 8081) &&
+ policy = _policy
+ policy_types_include_egress.call(policy) &&
+ exact_pod_selector.call(policy, { "clerum.io/managed-by" => "host-context-controller" }) &&
+ allows_tcp_port.call(rule, 8081) &&
Array(rule["to"]).any? do |peer|
peer.dig("namespaceSelector", "matchLabels", "kubernetes.io/metadata.name") == "control-plane" &&
peer.dig("podSelector", "matchLabels", "app") == "host-context-controller-api-gateway"
@@ -186,6 +269,7 @@ proxy_8083 = policy_rules.any? { |_policy, rule| allows_tcp_port.call(rule, 8083
puts JSON.generate(
"egress_contract_ok" => egress_contract_ok,
+ "selector_contract_ok" => selector_contract_ok,
"hcc_lane" => hcc_lane,
"proxy_8083" => proxy_8083,
)
diff --git a/scripts/security/verify-np08-hcc-authz.sh b/scripts/security/verify-np08-hcc-authz.sh
index 62635a0cd..e87271f75 100755
--- a/scripts/security/verify-np08-hcc-authz.sh
+++ b/scripts/security/verify-np08-hcc-authz.sh
@@ -8,6 +8,8 @@ set -euo pipefail
context=''
read_only=0
redact=0
+tmp_dir="$(mktemp -d "${TMPDIR:-/tmp}/np08-live-authz.XXXXXX")"
+trap 'rm -rf "${tmp_dir}"' EXIT
while [[ "$#" -gt 0 ]]; do
case "$1" in
--context)
@@ -70,11 +72,14 @@ check proxy_singleton_replicas "$([[ "${proxy_replicas}" == '1' ]] && echo 1 ||
check proxy_singleton_ready "$([[ "${proxy_ready}" == '1' ]] && echo 1 || echo 0)"
host_policy_json="$(kubectl --context="${context}" -n mcp-host get networkpolicies -o json)"
-network_policy_result="$(RUBYOPT=--disable=gems ruby "${BASH_SOURCE[0]%/*}/check-np08-mcp-host-networkpolicy.rb" <<<"${host_policy_json}")"
+kubectl --context="${context}" -n mcp-host get pods -o json >"${tmp_dir}/host-pods.json"
+network_policy_result="$(RUBYOPT=--disable=gems ruby "${BASH_SOURCE[0]%/*}/check-np08-mcp-host-networkpolicy.rb" --host-pods "${tmp_dir}/host-pods.json" <<<"${host_policy_json}")"
network_policy_ok="$(ruby -rjson -e 'puts(JSON.parse(STDIN.read)["egress_contract_ok"] ? 1 : 0)' <<<"${network_policy_result}")"
+selector_contract_ok="$(ruby -rjson -e 'puts(JSON.parse(STDIN.read)["selector_contract_ok"] ? 1 : 0)' <<<"${network_policy_result}")"
hcc_lane_ok="$(ruby -rjson -e 'puts(JSON.parse(STDIN.read)["hcc_lane"] ? 1 : 0)' <<<"${network_policy_result}")"
host_proxy_8083_ok="$(ruby -rjson -e 'puts(JSON.parse(STDIN.read)["proxy_8083"] ? 0 : 1)' <<<"${network_policy_result}")"
check mcp_host_egress_contract "${network_policy_ok}"
+check mcp_host_selector_contract "${selector_contract_ok}"
check hcc_gateway_egress_lane "${hcc_lane_ok}"
check no_host_proxy_8083_egress "${host_proxy_8083_ok}"
diff --git a/scripts/tests/test-minikube-pre-gate-sync-state.sh b/scripts/tests/test-minikube-pre-gate-sync-state.sh
index 4f9e0c9d6..6c0b133ae 100755
--- a/scripts/tests/test-minikube-pre-gate-sync-state.sh
+++ b/scripts/tests/test-minikube-pre-gate-sync-state.sh
@@ -154,11 +154,12 @@ else
fail "pre-gate does not verify the running NP-08 HCC gateway contract"
fi
+nginx_inspection_pipeline_lines="$(grep -F 'nginx -T' "$RUNTIME_SCRIPT" | grep -vE '^[[:space:]]*#' | grep -E '\\|[[:space:]]*(grep|rg|sed|awk|head|tail|cut|sort|tr|wc)([[:space:]]|$)' || true)"
if runtime_contains 'assert_workflow_gateway_prompt_bridge_finalization_route()' &&
runtime_contains 'nginx_config="$(${KC} exec' &&
runtime_contains 'could not inspect the active nginx configuration' &&
runtime_contains '[[ "${nginx_config}" != *"${expected_route}"* ]]' &&
- ! grep -F 'nginx -T' "$RUNTIME_SCRIPT" | grep -Fq '|'; then
+ [[ -z "$nginx_inspection_pipeline_lines" ]]; then
pass "pre-gate runtime guard separates nginx inspection from route validation"
else
fail "pre-gate runtime guard can confuse SIGPIPE or exec failure with a missing route"
diff --git a/scripts/tests/test-np08-live-networkpolicy-contract.sh b/scripts/tests/test-np08-live-networkpolicy-contract.sh
index 6a22847c6..635de7078 100755
--- a/scripts/tests/test-np08-live-networkpolicy-contract.sh
+++ b/scripts/tests/test-np08-live-networkpolicy-contract.sh
@@ -22,13 +22,17 @@ assert_result() {
local expected="$2"
local actual
actual="$(RUBYOPT=--disable=gems ruby "$helper" <"${fixture}")"
- if [[ "${actual}" != "${expected}" ]]; then
+ if ! ruby -rjson -e '
+ expected = JSON.parse(ARGV.fetch(0))
+ actual = JSON.parse(STDIN.read)
+ abort unless expected.all? { |key, value| actual[key] == value }
+ ' "${expected}" <<<"${actual}"; then
echo "FAIL: unexpected live NetworkPolicy result" >&2
exit 1
fi
}
-assert_result "${tmp_dir}/valid.json" '{"egress_contract_ok":true,"hcc_lane":true,"proxy_8083":false}'
+assert_result "${tmp_dir}/valid.json" '{"egress_contract_ok":true,"selector_contract_ok":true,"hcc_lane":true,"proxy_8083":false}'
echo "PASS: live policy helper accepts the current render"
mutate() {
@@ -86,3 +90,11 @@ echo "PASS: live policy helper rejects mcp-proxy TCP 8083"
proxy_range="$(mutate proxy-range 'data["items"].find { |d| d["metadata"]["name"] == "mcp-host" }["spec"]["egress"] << { "to" => [{ "namespaceSelector" => { "matchLabels" => { "kubernetes.io/metadata.name" => "control-plane" } }, "podSelector" => { "matchLabels" => { "app" => "host-context-controller-api-gateway" } } }], "ports" => [{ "port" => 8000, "endPort" => 9000, "protocol" => "TCP" }] }')"
assert_result "${proxy_range}" '{"egress_contract_ok":true,"hcc_lane":true,"proxy_8083":true}'
echo "PASS: live policy helper rejects a TCP range containing 8083"
+
+invalid_selector="$(mutate invalid-selector 'data["items"].select { |d| d["kind"] == "NetworkPolicy" && d.dig("metadata", "namespace") == "mcp-host" }.each { |d| d["spec"]["podSelector"] = { "matchLabels" => { "np08.invalid/never" => "true" } } }')"
+assert_result "${invalid_selector}" '{"egress_contract_ok":true,"selector_contract_ok":false,"hcc_lane":false,"proxy_8083":false}'
+echo "PASS: live policy helper rejects ineffective Host selectors"
+
+missing_egress_type="$(mutate missing-egress-type 'data["items"].find { |d| d["metadata"]["name"] == "mcp-host" }["spec"]["policyTypes"] = ["Ingress"]')"
+assert_result "${missing_egress_type}" '{"selector_contract_ok":false,"hcc_lane":false}'
+echo "PASS: live policy helper rejects a Host policy without Egress policy type"
diff --git a/scripts/tests/test-np08-render-contract-fixtures.sh b/scripts/tests/test-np08-render-contract-fixtures.sh
index a4bdc53b0..5068ddd46 100755
--- a/scripts/tests/test-np08-render-contract-fixtures.sh
+++ b/scripts/tests/test-np08-render-contract-fixtures.sh
@@ -102,6 +102,22 @@ when 'named-port'
'to' => [{ 'ipBlock' => { 'cidr' => '198.51.100.1/32' } }],
'ports' => [{ 'port' => 'mcp-http', 'protocol' => 'TCP' }],
}
+when 'invalid-host-selector'
+ policies = documents.select do |document|
+ document['kind'] == 'NetworkPolicy' && document.dig('metadata', 'namespace') == 'mcp-host'
+ end
+ abort('fixture source is missing mcp-host NetworkPolicies') if policies.empty?
+ policies.each do |policy|
+ policy['spec']['podSelector'] = { 'matchLabels' => { 'np08.invalid/never' => 'true' } }
+ end
+when 'missing-egress-policy-type'
+ policy = documents.find do |document|
+ document['kind'] == 'NetworkPolicy' &&
+ document.dig('metadata', 'namespace') == 'mcp-host' &&
+ document.dig('metadata', 'name') == 'mcp-host'
+ end
+ abort('fixture source is missing mcp-host NetworkPolicy') unless policy
+ policy['spec']['policyTypes'] = ['Ingress']
when 'host-secret-grant'
documents << {
'apiVersion' => 'rbac.authorization.k8s.io/v1',
@@ -149,6 +165,26 @@ when 'host-secret-user-grant', 'host-secret-group-grant'
},
'subjects' => [subject],
}
+when 'host-secret-authenticated-group-grant'
+ documents << {
+ 'apiVersion' => 'rbac.authorization.k8s.io/v1',
+ 'kind' => 'Role',
+ 'metadata' => { 'name' => 'fixture-host-secret-authenticated-reader', 'namespace' => 'mcp-server' },
+ 'rules' => [
+ { 'apiGroups' => [''], 'resources' => ['secrets'], 'verbs' => ['get'] },
+ ],
+ }
+ documents << {
+ 'apiVersion' => 'rbac.authorization.k8s.io/v1',
+ 'kind' => 'RoleBinding',
+ 'metadata' => { 'name' => 'fixture-host-secret-authenticated-reader', 'namespace' => 'mcp-server' },
+ 'roleRef' => {
+ 'apiGroup' => 'rbac.authorization.k8s.io',
+ 'kind' => 'Role',
+ 'name' => 'fixture-host-secret-authenticated-reader',
+ },
+ 'subjects' => [{ 'kind' => 'Group', 'name' => 'system:authenticated' }],
+ }
else
abort("unknown fixture mutation: #{mutation}")
end
@@ -210,6 +246,20 @@ assert_rejected \
'mcp-host egress must use numeric ports' \
'named mcp-host egress port'
+invalid_host_selector="${tmpdir}/invalid-host-selector.yaml"
+mutate_render invalid-host-selector "${invalid_host_selector}"
+assert_rejected \
+ "${invalid_host_selector}" \
+ 'mcp-host default-deny must select every pod and enforce Egress' \
+ 'mcp-host policies with ineffective selectors'
+
+missing_egress_policy_type="${tmpdir}/missing-egress-policy-type.yaml"
+mutate_render missing-egress-policy-type "${missing_egress_policy_type}"
+assert_rejected \
+ "${missing_egress_policy_type}" \
+ 'mcp-host allow policy must select HCC-managed Host pods and enforce Egress' \
+ 'mcp-host policy without Egress type'
+
host_secret_grant="${tmpdir}/host-secret-grant.yaml"
mutate_render host-secret-grant "${host_secret_grant}"
assert_rejected \
@@ -225,3 +275,10 @@ for identity in user group; do
'mcp-host identities must not receive MCP Secret read grants' \
"mcp-host MCP Secret ${identity} grant"
done
+
+host_secret_authenticated_group="${tmpdir}/host-secret-authenticated-group-grant.yaml"
+mutate_render host-secret-authenticated-group-grant "${host_secret_authenticated_group}"
+assert_rejected \
+ "${host_secret_authenticated_group}" \
+ 'mcp-host identities must not receive MCP Secret read grants' \
+ 'mcp-host MCP Secret system:authenticated grant'
diff --git a/scripts/tests/test-np08-render-contract.sh b/scripts/tests/test-np08-render-contract.sh
index 44eb0a943..433da1cc0 100755
--- a/scripts/tests/test-np08-render-contract.sh
+++ b/scripts/tests/test-np08-render-contract.sh
@@ -107,6 +107,33 @@ for rendered in "$@"; do
policies = documents.select do |document|
document["kind"] == "NetworkPolicy" && document.dig("metadata", "namespace") == "mcp-host"
end
+ policy_types_include_egress = lambda do |policy|
+ Array(policy.dig("spec", "policyTypes")).include?("Egress")
+ end
+ exact_pod_selector = lambda do |policy, expected_labels|
+ selector = policy.dig("spec", "podSelector")
+ selector.is_a?(Hash) && selector.keys.sort == ["matchLabels"] &&
+ selector["matchLabels"] == expected_labels && Array(selector["matchExpressions"]).empty?
+ end
+ default_deny = policies.find { |policy| policy.dig("metadata", "name") == "deny-all-mcp-host" }
+ abort("mcp-host default-deny must select every pod and enforce Egress") unless
+ default_deny && default_deny.dig("spec", "podSelector") == {} && policy_types_include_egress.call(default_deny)
+ managed_host_policy = policies.find { |policy| policy.dig("metadata", "name") == "mcp-host" }
+ abort("mcp-host allow policy must select HCC-managed Host pods and enforce Egress") unless
+ managed_host_policy && exact_pod_selector.call(managed_host_policy, { "clerum.io/managed-by" => "host-context-controller" }) &&
+ policy_types_include_egress.call(managed_host_policy)
+ context_allow_policies = policies.select do |policy|
+ policy.dig("metadata", "labels", "clerum.io/policy-type") == "context-allow"
+ end
+ context_allow_policies.each do |policy|
+ source_labels = policy.dig("spec", "podSelector", "matchLabels")
+ context = policy.dig("metadata", "labels", "clerum.io/context")
+ abort("context-allow policy does not select its live Context Host pods") unless
+ source_labels.is_a?(Hash) && source_labels["clerum.io/managed-by"] == "host-context-controller" &&
+ source_labels["clerum.io/context"] == context &&
+ Array(policy.dig("spec", "podSelector", "matchExpressions")).empty? &&
+ policy_types_include_egress.call(policy)
+ end
broad_host_egress = policies.any? do |policy|
Array(policy.dig("spec", "egress")).any? do |rule|
!rule.key?("to") || Array(rule["to"]).empty? ||
@@ -242,6 +269,8 @@ for rendered in "$@"; do
abort("mcp-host egress must use numeric ports") if named_port
hcc_lane = policies.any? do |policy|
+ next false unless policy_types_include_egress.call(policy) &&
+ exact_pod_selector.call(policy, { "clerum.io/managed-by" => "host-context-controller" })
Array(policy.dig("spec", "egress")).any? do |rule|
ports = Array(rule["ports"])
peers = Array(rule["to"])
@@ -300,7 +329,7 @@ for rendered in "$@"; do
when "User"
subject["name"].to_s.match?(/\Asystem:serviceaccount:mcp-host:[^:]+\z/)
when "Group"
- %w[system:serviceaccounts system:serviceaccounts:mcp-host].include?(subject["name"])
+ %w[system:authenticated system:serviceaccounts system:serviceaccounts:mcp-host].include?(subject["name"])
else
false
end