Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(helm): limit the remote lanes' network access with a NetworkPolicy (#498)
Krisztian Gajdarf81fab384a1c
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 0de26077a..e9cba89b2 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -759,7 +759,7 @@ routes every remote profile there, through the normal queue, because the`remote` bundle outranks `default` for the remote adapters. The gateway holdsno upstream credential and calls no upstream.-Enable the remote pool and the worker NetworkPolicy, and define the upstreams:+Enable the remote pool and define the upstreams:```yamlupstreams:@@ -773,8 +773,6 @@ upstreams:requests_per_minute: 600max_concurrency: 32workers:- networkPolicy:- enabled: truepools:remote:enabled: true@@ -807,14 +805,11 @@ Below, `<fullname>` is the chart's full name: `<release>-sie-cluster`, orupstream's Secret key must also differ from every Secret key the charthands to another component (the Hugging Face token, the gateway tokens, thesie-config tokens and the NATS passwords).-- **A remote lane needs `workers.networkPolicy.enabled: true`, and the render- fails without it.** The worker API has no authentication of its own, so- without a NetworkPolicy any pod in the cluster, including worker lanes that- run model code, could call a remote lane directly and spend its- credentials. The policy admits only this release's gateway pods, and needs- a CNI that enforces NetworkPolicy. Because it also selects the remote lane,- `workers.networkPolicy.extraIngress` cannot be set while a remote lane is- enabled.+- **A remote lane needs a NetworkPolicy, and the render fails without one.**+ The worker API has no authentication of its own, so without a policy any pod+ in the cluster, including worker lanes that run model code, could call a+ remote lane directly and spend its credentials. The remote lanes' own policy+ is on by default; see [Network policy for remote lanes](#network-policy-for-remote-lanes).- Remote lanes run as their own ServiceAccount, `<fullname>-worker-remote`,with no Kubernetes API token, no cloud workload identity and no`HF_TOKEN`. Without an identity they cannot read the payload store, so a@@ -837,6 +832,108 @@ Below, `<fullname>` is the chart's full name: `<release>-sie-cluster`, or`kubectl rollout restart statefulset/<fullname>-worker-remote-remote`.A change to `upstreams` restarts it automatically.+#### Network policy for remote lanes++When a remote lane is enabled, the chart renders a `NetworkPolicy` for the+remote lanes' pods (`workers.remote.networkPolicy.enabled`, on by default).+A remote lane needs this policy or `workers.networkPolicy`, and the render+fails when both are off. The policy takes effect only with a CNI that enforces+NetworkPolicy.++- **Ingress:** only this release's gateway pods, on the worker ports. The worker+ API has no authentication of its own, so without this rule any pod in the+ cluster could call a remote lane directly and spend its upstream credentials.+ While this policy is on, `workers.networkPolicy` excludes the remote lanes, so+ its `extraIngress` sources cannot reach them. NetworkPolicies are additive:+ any other policy that selects these pods and admits more sources widens+ access.+- **Egress:** port 53 to the cluster resolver (`dnsTo`, by default the+ `kube-dns` pods in `kube-system`); this release's NATS (4222), sie-config and+ gateway (8080), telemetry collector (4327) and bundled Tempo (4317) pods; and+ TCP 443 plus each upstream's explicit port, or its `proxy_url`'s explicit+ port when a proxy carries its traffic, to `allowedCidrs` (every address by+ default) except the denied ranges. A URL without a port adds nothing beyond+ 443, so give an `http` `proxy_url` its port explicitly or admit the proxy with+ `extraEgress`. Nothing else is allowed.+- **Denied ranges:** a fixed base that values cannot remove: the private ranges+ (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), the carrier-grade NAT range+ (100.64.0.0/10), link-local (169.254.0.0/16, which holds the cloud metadata+ services), 168.63.129.16, IPv6 unique-local (fc00::/7) and link-local+ (fe80::/10), and the NAT64 prefixes (64:ff9b::/96, 64:ff9b:1::/48). Add more+ with `extraDeniedCidrs`. Each IPv4 entry of `allowedCidrs` excludes the denied+ ranges inside it, an entry inside a denied range fails the render, and the+ only IPv6 entry is `::/0`. A denial equal to an allowed range also fails.+ Every CIDR must use its network address; IPv4-mapped IPv6 addresses are+ rejected because Kubernetes treats them as IPv4.++**What the policy does not do.** NetworkPolicy matches addresses and ports, not+host names. The remote lanes can reach any address outside the denied ranges on+the allowed ports, not only the upstreams you declared. To limit egress to the+declared hosts, use a policy engine with DNS-aware rules (for example Cilium or+Calico), or route upstream traffic through an egress proxy that enforces a host+allowlist: set the upstream's `proxy_url`, set `allowedCidrs: []`, and admit the+proxy, and the payload store if you use one, with `extraEgress`. Port 53 is open+only to `dnsTo`, but data tunnelled through the resolver itself is out of scope.++Kubernetes does not apply NetworkPolicy to traffic from a pod's own node, so+the node and `hostNetwork` pods on a remote lane's node can still reach the+worker port. An IPv6 cluster that gives pods global addresses must add its pod+range to `extraDeniedCidrs`.++Some deployments need an `extraEgress` rule, because the policy blocks the+destination:++- **NATS outside this release** (`nats.install: false`).+- **Private endpoints.** A payload store or an upstream reached through a+ private endpoint, such as AWS PrivateLink or an Azure private endpoint, has an+ address in the private ranges.+- **Carrier-grade NAT addresses.** Alibaba Cloud's internal OSS endpoints+ resolve to addresses in 100.64.0.0/10, and some clusters assign pod addresses+ from that range. Admit the specific endpoint range, not the whole block: the+ Alibaba Cloud metadata service is also in it, at 100.100.100.200.+- **Pod identity through a node-local endpoint.** GKE Workload Identity reads+ credentials from the GKE metadata server: 169.254.169.254 on TCP port 80+ with Dataplane V2, or 169.254.169.252 on TCP port 988 without Dataplane V2.+ EKS Pod Identity reads them from its agent (169.254.170.23, port 80).+ The policy blocks these endpoints,+ so a remote lane given an identity through+ `workers.remote.serviceAccount.annotations` cannot obtain it until you admit+ that one address and port. EKS IRSA, AKS workload identity and Alibaba Cloud+ RRSA exchange a projected token at the provider's token endpoint on port 443;+ they need a rule only when that endpoint has a private or carrier-grade NAT+ address, such as a VPC endpoint.+- **An OTLP endpoint other than this release's collector or Tempo**, inside or+ outside the cluster. Without a rule, the remote lanes' telemetry is dropped.+- **A NodeLocal DNSCache**: add its address to `dnsTo` as an `ipBlock`.++For GKE Workload Identity with Dataplane V2:++```yaml+workers:+ remote:+ networkPolicy:+ extraEgress:+ - to:+ - ipBlock:+ cidr: 169.254.169.254/32+ ports:+ - port: 80+ protocol: TCP+```++Without Dataplane V2, use `cidr: 169.254.169.252/32` and `port: 988` instead,+as described in the [GKE Workload Identity documentation](https://docs.cloud.google.com/kubernetes-engine/docs/concepts/workload-identity).++Admit 169.254.169.254 only where it serves workload identity, as on GKE with+Workload Identity enabled. On nodes without it, this address serves the node's+own credentials to any pod that can reach it.++Each `extraEgress` rule needs a non-empty `to` (a scoped selector, or an+`ipBlock` with a prefix length above /0) and `ports` (each with a port, and no+range wider than 60000 ports). With `workers.remote.networkPolicy.enabled:+false`, `workers.networkPolicy` must be on; it then limits who can reach the+remote lanes, and their egress is not restricted.+### High availability in one file`values-ha.yaml` is the tested composition of the durability knobs below withdiff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txtindex 6ff0fe3a4..db84cad8a 100644--- a/deploy/helm/sie-cluster/templates/NOTES.txt+++ b/deploy/helm/sie-cluster/templates/NOTES.txt@@ -44,6 +44,18 @@ Grafana password: kubectl get secret -n {{ include "sie-cluster.kubePrometheusSt{{- if .Values.keda.install }}KEDA: enabled{{- end }}+{{- if eq (include "sie-cluster.worker.remoteLaneEnabled" .) "true" }}++Remote backends: the remote lane is the only worker that holds upstream credentials.+{{- if dig "remote" "networkPolicy" "enabled" true .Values.workers }}+Its NetworkPolicy admits only the gateway and limits egress by address and port, not by host name.+It works only with a CNI that enforces NetworkPolicy. See the chart README section "Network policy+for remote lanes".+{{- else }}+WARNING: workers.remote.networkPolicy.enabled=false. workers.networkPolicy still limits who can+reach the remote lane, but its egress is not restricted.+{{- end }}+{{- end }}{{- if and .Release.IsUpgrade (not .Values.ingress.enabled) (lookup "networking.k8s.io/v1" "Ingress" (include "sie-cluster.namespace" .) (include "sie-cluster.fullname" .)) }}WARNING: this upgrade removes the gateway Ingress {{ include "sie-cluster.fullname" . }} becausediff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 6484ec773..1c9f2d8ba 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -1350,6 +1350,212 @@ is sent, and the gateway's Role may write every ConfigMap in the namespace.{{- printf "%s-worker-remote" (include "sie-cluster.fullname" .) -}}{{- end }}+{{/*+"true" when the remote lanes' own NetworkPolicy renders: a remote lane is+enabled and workers.remote.networkPolicy.enabled is not false.+*/}}+{{- define "sie-cluster.worker.remoteNetworkPolicyEnabled" -}}+{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" .) "true") (dig "remote" "networkPolicy" "enabled" true .Values.workers) -}}+true+{{- end -}}+{{- end }}++{{/*+Ranges the remote lanes never reach through allowedCidrs, as a JSON list: a+fixed base that values cannot remove (private, carrier-grade NAT, link-local+and metadata addresses, IPv6 unique-local, link-local and NAT64 prefixes),+followed by workers.remote.networkPolicy.extraDeniedCidrs.+*/}}+{{- define "sie-cluster.worker.remoteDeniedCidrs" -}}+{{- $denied := list "10.0.0.0/8" "172.16.0.0/12" "192.168.0.0/16" "100.64.0.0/10" "169.254.0.0/16" "168.63.129.16/32" "fc00::/7" "fe80::/10" "64:ff9b::/96" "64:ff9b:1::/48" -}}+{{- range $index, $cidr := (dig "remote" "networkPolicy" "extraDeniedCidrs" list .Values.workers) -}}+{{- if not (and (kindIs "string" $cidr) (regexMatch "^[0-9A-Fa-f:.]+/[0-9]{1,3}$" $cidr)) -}}+{{- fail (printf "workers.remote.networkPolicy.extraDeniedCidrs[%d] must be a CIDR" $index) -}}+{{- end -}}+{{- $validator := ternary "sie-cluster.cidr.ipv6" "sie-cluster.cidr.ipv4" (contains ":" $cidr) -}}+{{- $_ := include $validator (dict "cidr" $cidr "field" (printf "workers.remote.networkPolicy.extraDeniedCidrs[%d]" $index)) -}}+{{- $denied = append $denied $cidr -}}+{{- end -}}+{{- toJson $denied -}}+{{- end }}++{{/*+An IPv4 CIDR as JSON {"ip": <address as an integer>, "prefix": <length>}.+Args (dict): cidr, field.+*/}}+{{- define "sie-cluster.cidr.ipv4" -}}+{{- $octet := "(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])" -}}+{{- if not (regexMatch (printf "^%s\\.%s\\.%s\\.%s/(3[0-2]|[12]?[0-9])$" $octet $octet $octet $octet) .cidr) -}}+{{- fail (printf "%s must be an IPv4 CIDR" .field) -}}+{{- end -}}+{{- $parts := regexSplit "[./]" .cidr -1 -}}+{{- $ip := add (mul (atoi (index $parts 0)) 16777216) (mul (atoi (index $parts 1)) 65536) (mul (atoi (index $parts 2)) 256) (atoi (index $parts 3)) -}}+{{- $prefix := atoi (index $parts 4) -}}+{{- $scale := 1 -}}+{{- range until (int (sub 32 $prefix)) -}}+{{- $scale = mul $scale 2 -}}+{{- end -}}+{{- if ne (mod $ip $scale) 0 -}}+{{- fail (printf "%s must be an IPv4 CIDR with a network address" .field) -}}+{{- end -}}+{{- dict "ip" $ip "prefix" $prefix | toJson -}}+{{- end }}++{{/*+Validate an IPv6 CIDR and return its prefix as JSON. IPv4 tails occupy two+hextets; :: must compress at least one. Args (dict): cidr, field.+*/}}+{{- define "sie-cluster.cidr.ipv6" -}}+{{- $field := .field -}}+{{- if not (and (kindIs "string" .cidr) (regexMatch "^[0-9A-Fa-f:.]+/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$" .cidr)) -}}+{{- fail (printf "%s must be an IPv6 CIDR" $field) -}}+{{- end -}}+{{- $cidrParts := splitList "/" .cidr -}}+{{- $address := first $cidrParts -}}+{{- if contains "." $address -}}+{{- $tail := last (splitList ":" $address) -}}+{{- $v4 := include "sie-cluster.cidr.ipv4" (dict "cidr" (printf "%s/32" $tail) "field" $field) | fromJson -}}+{{- $address = printf "%s%x:%x" (trimSuffix $tail $address) (int (div (int64 $v4.ip) 65536)) (int (mod (int64 $v4.ip) 65536)) -}}+{{- end -}}+{{- $parts := splitList "::" $address -}}+{{- $groups := list -}}+{{- range $part := $parts -}}+{{- if $part -}}+{{- $groups = concat $groups (splitList ":" $part) -}}+{{- end -}}+{{- end -}}+{{- range $group := $groups -}}+{{- if not (regexMatch "^[0-9A-Fa-f]{1,4}$" $group) -}}+{{- fail (printf "%s must be an IPv6 CIDR" $field) -}}+{{- end -}}+{{- end -}}+{{- if not (or (and (eq (len $parts) 1) (eq (len $groups) 8)) (and (eq (len $parts) 2) (lt (len $groups) 8))) -}}+{{- fail (printf "%s must be an IPv6 CIDR" $field) -}}+{{- end -}}+{{- if eq (len $parts) 2 -}}+{{- $expanded := regexFindAll "[0-9A-Fa-f]+" (first $parts) -1 -}}+{{- range until (int (sub 8 (len $groups))) -}}+{{- $expanded = append $expanded "0" -}}+{{- end -}}+{{- $groups = concat $expanded (regexFindAll "[0-9A-Fa-f]+" (last $parts) -1) -}}+{{- end -}}+{{- $digits := dict "0" 0 "1" 1 "2" 2 "3" 3 "4" 4 "5" 5 "6" 6 "7" 7 "8" 8 "9" 9 "a" 10 "b" 11 "c" 12 "d" 13 "e" 14 "f" 15 -}}+{{- $values := list -}}+{{- range $group := $groups -}}+{{- $value := 0 -}}+{{- range $digit := splitList "" (lower $group) -}}+{{- $value = add (mul $value 16) (get $digits $digit) -}}+{{- end -}}+{{- $values = append $values $value -}}+{{- end -}}+{{- if and (eq (index $values 0) 0) (eq (index $values 1) 0) (eq (index $values 2) 0) (eq (index $values 3) 0) (eq (index $values 4) 0) (eq (index $values 5) 65535) -}}+{{- fail (printf "%s must be an IPv6 CIDR without an IPv4-mapped address" $field) -}}+{{- end -}}+{{- $prefix := atoi (last $cidrParts) -}}+{{- range $index, $value := $values -}}+{{- $bits := max 0 (min 16 (sub $prefix (mul $index 16))) -}}+{{- $scale := 1 -}}+{{- range until (int (sub 16 $bits)) -}}+{{- $scale = mul $scale 2 -}}+{{- end -}}+{{- if ne (mod $value $scale) 0 -}}+{{- fail (printf "%s must be an IPv6 CIDR with a network address" $field) -}}+{{- end -}}+{{- end -}}+{{- dict "prefix" $prefix | toJson -}}+{{- end }}++{{/*+"true" when the IPv4 block `inner` lies inside `outer`. Two CIDR blocks are+either nested or disjoint. Args (dict): inner, outer (from sie-cluster.cidr.ipv4).+*/}}+{{- define "sie-cluster.cidr.ipv4Within" -}}+{{- if ge (int .inner.prefix) (int .outer.prefix) -}}+{{- $scale := 1 -}}+{{- range until (int (sub 32 (int .outer.prefix))) -}}+{{- $scale = mul $scale 2 -}}+{{- end -}}+{{- if eq (div (int64 .inner.ip) $scale) (div (int64 .outer.ip) $scale) -}}+true+{{- end -}}+{{- end -}}+{{- end }}++{{/*+Fail unless every NetworkPolicy peer is scoped: a podSelector or+namespaceSelector with matchLabels or matchExpressions, or an ipBlock whose+prefix length is above 0. Args (dict): peers, path.+*/}}+{{- define "sie-cluster.networkPolicy.validatePeers" -}}+{{- $path := .path -}}+{{- range $index, $peer := .peers -}}+{{- $scoped := false -}}+{{- if kindIs "map" $peer -}}+{{- if and (hasKey $peer "ipBlock") (or (hasKey $peer "podSelector") (hasKey $peer "namespaceSelector")) -}}+{{- fail (printf "%s[%d] cannot combine ipBlock with podSelector or namespaceSelector." $path $index) -}}+{{- end -}}+{{- range $selectorKey := list "podSelector" "namespaceSelector" -}}+{{- $selector := index $peer $selectorKey -}}+{{- if and (kindIs "map" $selector) (or $selector.matchLabels $selector.matchExpressions) -}}+{{- $scoped = true -}}+{{- end -}}+{{- end -}}+{{- if $peer.ipBlock -}}+{{- $cidr := toString (dig "cidr" "" (default (dict) $peer.ipBlock)) -}}+{{- if or (not $cidr) (regexMatch "/0+$" (trim $cidr)) -}}+{{- fail (printf "%s[%d] admits every address: give the ipBlock a prefix length above 0." $path $index) -}}+{{- end -}}+{{- $validator := ternary "sie-cluster.cidr.ipv6" "sie-cluster.cidr.ipv4" (contains ":" $cidr) -}}+{{- $_ := include $validator (dict "cidr" $cidr "field" (printf "%s[%d].ipBlock.cidr" $path $index)) -}}+{{- $scoped = true -}}+{{- end -}}+{{- end -}}+{{- if not $scoped -}}+{{- fail (printf "%s[%d] admits every destination: give it a podSelector or namespaceSelector with matchLabels or matchExpressions, or an ipBlock." $path $index) -}}+{{- end -}}+{{- end -}}+{{- end }}++{{/*+Fail unless every NetworkPolicy port names a port and spans at most 60000+ports. Args (dict): ports, path.+*/}}+{{- define "sie-cluster.networkPolicy.validatePorts" -}}+{{- $path := .path -}}+{{- range $index, $port := .ports -}}+{{- if not (and (kindIs "map" $port) $port.port) -}}+{{- fail (printf "%s[%d] admits every port: set port." $path $index) -}}+{{- end -}}+{{- $numeric := or (kindIs "int" $port.port) (kindIs "int64" $port.port) (kindIs "float64" $port.port) -}}+{{- if $numeric -}}+{{- if not (and (eq (float64 $port.port) (floor (float64 $port.port))) (ge (float64 $port.port) 1.0) (le (float64 $port.port) 65535.0)) -}}+{{- fail (printf "%s[%d].port must be an integer between 1 and 65535." $path $index) -}}+{{- end -}}+{{- end -}}+{{- if not (kindIs "invalid" $port.endPort) -}}+{{- $integral := list -}}+{{- range $value := list $port.port $port.endPort -}}+{{- $integral = append $integral (or (kindIs "int" $value) (kindIs "int64" $value) (and (kindIs "float64" $value) (eq (float64 $value) (floor (float64 $value))))) -}}+{{- end -}}+{{- if not (index $integral 0) -}}+{{- fail (printf "%s[%d] sets endPort, which needs a numeric port, not a named one." $path $index) -}}+{{- end -}}+{{- if not (index $integral 1) -}}+{{- fail (printf "%s[%d].endPort must be an integer." $path $index) -}}+{{- end -}}+{{- if or (lt (int64 $port.endPort) 1) (gt (int64 $port.endPort) 65535) -}}+{{- fail (printf "%s[%d].endPort must be between 1 and 65535." $path $index) -}}+{{- end -}}+{{- if lt (int64 $port.endPort) (int64 $port.port) -}}+{{- fail (printf "%s[%d].endPort must be at least port." $path $index) -}}+{{- end -}}+{{- if gt (sub (int64 $port.endPort) (int64 $port.port)) 60000 -}}+{{- fail (printf "%s[%d] spans nearly every port: list the ports instead." $path $index) -}}+{{- end -}}+{{- end -}}+{{- end -}}+{{- end }}+{{/*Environment variable that carries one upstream's credential on remote lanes.Upstream names hold no underscore, so the mapping is one to one.@@ -1740,11 +1946,11 @@ credential pasted as a key would otherwise be printed.{{- end -}}{{- end -}}{{- end -}}-{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" $root) "true") (not (dig "networkPolicy" "enabled" false $root.Values.workers)) -}}-{{- fail "a remote lane needs workers.networkPolicy.enabled=true. The worker API has no authentication of its own, so without a NetworkPolicy any pod in the cluster could call a remote lane directly and spend its upstream credentials." -}}+{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" $root) "true") (not (dig "networkPolicy" "enabled" false $root.Values.workers)) (ne (include "sie-cluster.worker.remoteNetworkPolicyEnabled" $root) "true") -}}+{{- fail "a remote lane needs a NetworkPolicy: keep workers.remote.networkPolicy.enabled=true (the default) or set workers.networkPolicy.enabled=true. The worker API has no authentication of its own, so without a NetworkPolicy any pod in the cluster could call a remote lane directly and spend its upstream credentials." -}}{{- end -}}-{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" $root) "true") (dig "networkPolicy" "extraIngress" list $root.Values.workers) -}}-{{- fail "workers.networkPolicy.extraIngress cannot be set while a remote lane is enabled: workers.networkPolicy also selects the remote lane, so every extraIngress source could call it directly and spend its upstream credentials." -}}+{{- if and (eq (include "sie-cluster.worker.remoteLaneEnabled" $root) "true") (ne (include "sie-cluster.worker.remoteNetworkPolicyEnabled" $root) "true") (dig "networkPolicy" "extraIngress" list $root.Values.workers) -}}+{{- fail "workers.networkPolicy.extraIngress cannot be set while a remote lane is enabled and workers.remote.networkPolicy.enabled is false: workers.networkPolicy then also selects the remote lane, so every extraIngress source could call it directly and spend its upstream credentials." -}}{{- end -}}{{- end }}diff --git a/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml b/deploy/helm/sie-cluster/templates/worker-networkpolicy.yamlindex 1ef71f3c8..1f41dc89c 100644--- a/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml+++ b/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml@@ -46,6 +46,14 @@ spec:podSelector:matchLabels:{{- include "sie-cluster.worker.selectorLabels" . | nindent 6 }}+ {{- if eq (include "sie-cluster.worker.remoteNetworkPolicyEnabled" .) "true" }}+ # The remote lanes have their own policy; extraIngress must not reach them.+ matchExpressions:+ - key: sie.superlinked.com/bundle+ operator: NotIn+ values:+ - remote+ {{- end }}policyTypes:- Ingressingress:diff --git a/deploy/helm/sie-cluster/templates/worker-remote-networkpolicy.yaml b/deploy/helm/sie-cluster/templates/worker-remote-networkpolicy.yamlnew file mode 100644index 000000000..1bdc69553--- /dev/null+++ b/deploy/helm/sie-cluster/templates/worker-remote-networkpolicy.yaml@@ -0,0 +1,165 @@+{{- $root := . -}}+{{- if eq (include "sie-cluster.worker.remoteNetworkPolicyEnabled" $root) "true" }}+{{- $policy := dig "remote" "networkPolicy" dict $root.Values.workers -}}+{{- $dnsTo := dig "dnsTo" list $policy -}}+{{- if not (and (kindIs "slice" $dnsTo) $dnsTo) -}}+{{- fail "workers.remote.networkPolicy.dnsTo needs at least one peer: the cluster resolver the remote lanes may query." -}}+{{- end -}}+{{- include "sie-cluster.networkPolicy.validatePeers" (dict "peers" $dnsTo "path" "workers.remote.networkPolicy.dnsTo") -}}+{{- range $index, $rule := (default list $policy.extraEgress) }}+{{- if not (and (kindIs "map" $rule) $rule.to $rule.ports) }}+{{- fail (printf "workers.remote.networkPolicy.extraEgress[%d] needs a non-empty to and ports: a rule without them admits every destination or every port." $index) }}+{{- end }}+{{- include "sie-cluster.networkPolicy.validatePeers" (dict "peers" $rule.to "path" (printf "workers.remote.networkPolicy.extraEgress[%d].to" $index)) }}+{{- include "sie-cluster.networkPolicy.validatePorts" (dict "ports" $rule.ports "path" (printf "workers.remote.networkPolicy.extraEgress[%d].ports" $index)) }}+{{- end }}+{{- $deniedV4 := list }}+{{- $deniedV6 := list }}+{{- range $cidr := (include "sie-cluster.worker.remoteDeniedCidrs" $root | fromJsonArray) }}+{{- if contains ":" $cidr }}+{{- $deniedV6 = append $deniedV6 $cidr }}+{{- else }}+{{- $deniedV4 = append $deniedV4 $cidr }}+{{- end }}+{{- end }}+{{- $allowed := list }}+{{- range $index, $cidr := (default list $policy.allowedCidrs) }}+{{- $field := printf "workers.remote.networkPolicy.allowedCidrs[%d]" $index }}+{{- if not (kindIs "string" $cidr) }}+{{- fail (printf "%s must be a CIDR string" $field) }}+{{- end }}+{{- if contains ":" $cidr }}+{{- if ne $cidr "::/0" }}+{{- fail (printf "%s: the only IPv6 entry is ::/0, which carries every denied IPv6 range as an exception. Admit a narrower IPv6 destination with extraEgress." $field) }}+{{- end }}+{{- range $deniedCidr := $deniedV6 }}+{{- $denied := include "sie-cluster.cidr.ipv6" (dict "cidr" $deniedCidr "field" "a denied range") | fromJson }}+{{- if eq (int $denied.prefix) 0 }}+{{- fail (printf "%s lies inside the denied range %s. Admit a private destination with extraEgress." $field $deniedCidr) }}+{{- end }}+{{- end }}+{{- $allowed = append $allowed (dict "cidr" $cidr "except" $deniedV6) }}+{{- else }}+{{- $block := include "sie-cluster.cidr.ipv4" (dict "cidr" $cidr "field" $field) | fromJson }}+{{- $except := list }}+{{- range $deniedCidr := $deniedV4 }}+{{- $denied := include "sie-cluster.cidr.ipv4" (dict "cidr" $deniedCidr "field" "a denied range") | fromJson }}+{{- if eq (include "sie-cluster.cidr.ipv4Within" (dict "inner" $block "outer" $denied)) "true" }}+{{- fail (printf "%s lies inside the denied range %s. Admit a private destination with extraEgress." $field $deniedCidr) }}+{{- else if eq (include "sie-cluster.cidr.ipv4Within" (dict "inner" $denied "outer" $block)) "true" }}+{{- $except = append $except $deniedCidr }}+{{- end }}+{{- end }}+{{- $allowed = append $allowed (dict "cidr" $cidr "except" $except) }}+{{- end }}+{{- end }}+{{- /* The ports of what the lane connects to directly: 443, and each upstream's+ explicit port, or its proxy's when a proxy carries its traffic. A URL+ without a port adds nothing, and a loopback upstream needs no egress. */ -}}+{{- $ports := list 443 }}+{{- range $name, $upstream := (default dict $root.Values.upstreams) }}+{{- $url := $upstream.proxy_url | default $upstream.base_url | toString }}+{{- $authority := regexReplaceAll "^[A-Za-z]+://([^/]*).*$" $url "${1}" }}+{{- if not (regexMatch "(?i)^(localhost|127\\.[0-9.]+|\\[::1\\])(:[0-9]*)?$" $authority) }}+{{- with regexFind ":[0-9]+$" $authority }}+{{- $port := trimPrefix ":" . | atoi }}+{{- if not (has $port $ports) }}+{{- $ports = append $ports $port }}+{{- end }}+{{- end }}+{{- end }}+{{- end }}+{{- $maxWorkerChildCount := int (include "sie-cluster.worker.maxChildCount" $root) }}+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: {{ include "sie-cluster.fullname" $root }}-worker-remote+ namespace: {{ include "sie-cluster.namespace" $root }}+ labels:+ {{- include "sie-cluster.worker.labels" $root | nindent 4 }}+spec:+ podSelector:+ matchLabels:+ {{- include "sie-cluster.worker.selectorLabels" $root | nindent 6 }}+ sie.superlinked.com/bundle: remote+ policyTypes:+ - Ingress+ - Egress+ ingress:+ - from:+ - podSelector:+ matchLabels:+ {{- include "sie-cluster.gateway.selectorLabels" $root | nindent 14 }}+ ports:+ {{- range $i := until $maxWorkerChildCount }}+ - port: {{ add $root.Values.workers.common.port $i }}+ protocol: TCP+ {{- end }}+ egress:+ - to:+ {{- toYaml $dnsTo | nindent 8 }}+ ports:+ - port: 53+ protocol: UDP+ - port: 53+ protocol: TCP+ {{- if $root.Values.nats.install }}+ - to:+ - podSelector:+ matchLabels:+ app.kubernetes.io/name: nats+ app.kubernetes.io/instance: {{ $root.Release.Name }}+ ports:+ - port: 4222+ protocol: TCP+ {{- end }}+ - to:+ - podSelector:+ matchLabels:+ {{- include "sie-cluster.config.selectorLabels" $root | nindent 14 }}+ - podSelector:+ matchLabels:+ {{- include "sie-cluster.gateway.selectorLabels" $root | nindent 14 }}+ ports:+ - port: 8080+ protocol: TCP+ {{- if eq (include "sie-cluster.otel.collectorEnabled" $root) "true" }}+ - to:+ - podSelector:+ matchLabels:+ {{- include "sie-cluster.selectorLabels" $root | nindent 14 }}+ app.kubernetes.io/component: otel-collector+ ports:+ - port: 4327+ protocol: TCP+ {{- end }}+ {{- if $root.Values.observability.tracing.tempo.install }}+ - to:+ - podSelector:+ matchLabels:+ app.kubernetes.io/name: tempo+ app.kubernetes.io/instance: {{ $root.Release.Name }}+ ports:+ - port: 4317+ protocol: TCP+ {{- end }}+ {{- with $allowed }}+ - to:+ {{- range $block := . }}+ - ipBlock:+ cidr: {{ $block.cidr | quote }}+ {{- with $block.except }}+ except:+ {{- toYaml . | nindent 14 }}+ {{- end }}+ {{- end }}+ ports:+ {{- range $port := $ports }}+ - port: {{ $port }}+ protocol: TCP+ {{- end }}+ {{- end }}+ {{- with $policy.extraEgress }}+ {{- toYaml . | nindent 4 }}+ {{- end }}+{{- end }}diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 11c442728..074c78bce 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -881,8 +881,10 @@ workers:# NetworkPolicies are additive: any other policy that selects worker pods# and admits more sources widens access, so check for overlapping policies.# Disabled by default; values-ha.yaml enables it. A remote lane- # (workers.pools.remote) requires it, with extraIngress empty, because any- # pod that reaches a remote lane could spend its upstream credentials.+ # (workers.pools.remote) requires this policy or workers.remote.networkPolicy.+ # When workers.remote.networkPolicy is enabled, this policy excludes remote+ # lanes. Otherwise extraIngress must be empty, because any pod that reaches+ # a remote lane could spend its upstream credentials.networkPolicy:enabled: false# -- Additional NetworkPolicy ingress rules for callers outside this chart@@ -909,6 +911,50 @@ workers:# iam.gke.io/gcp-service-account).serviceAccount:annotations: {}+ # -- NetworkPolicy for the remote lanes' pods, rendered whenever a remote+ # lane is enabled. Ingress: only this release's gateway pods, on the worker+ # ports; the generic workers.networkPolicy then excludes the remote lanes.+ # Egress: DNS to dnsTo; this release's NATS, sie-config, gateway,+ # telemetry collector and bundled Tempo; and TCP 443 plus each upstream's+ # explicit port (its proxy's, when it has one), to allowedCidrs except the+ # denied ranges. It matches addresses and ports, not host names, and needs+ # a CNI that enforces NetworkPolicy. See the chart README section "Network+ # policy for remote lanes". A remote lane needs this policy or+ # workers.networkPolicy.+ networkPolicy:+ enabled: true+ # -- Destinations for TCP 443 and the upstream ports. Each IPv4 entry+ # excludes the denied ranges inside it, and an entry inside a denied range+ # fails the render. The only IPv6 entry is ::/0. An empty list renders no+ # such rule.+ allowedCidrs:+ - 0.0.0.0/0+ - ::/0+ # -- Ranges excluded in addition to the fixed base, which values cannot+ # remove: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 100.64.0.0/10,+ # 169.254.0.0/16, 168.63.129.16/32, fc00::/7, fe80::/10, 64:ff9b::/96 and+ # 64:ff9b:1::/48. Add your cluster's pod and service ranges if they lie+ # outside the base, for example global IPv6 pod addresses. Every CIDR+ # must use its network address; IPv4-mapped IPv6 addresses are rejected.+ extraDeniedCidrs: []+ # -- The cluster resolver the remote lanes may query on port 53. The+ # default is the kube-dns pods most distributions run. Add NodeLocal+ # DNSCache's address (for example 169.254.20.10/32) as an ipBlock when+ # the cluster uses it. Each entry needs a scoped selector or an ipBlock.+ dnsTo:+ - namespaceSelector:+ matchLabels:+ kubernetes.io/metadata.name: kube-system+ podSelector:+ matchLabels:+ k8s-app: kube-dns+ # -- Additional egress rules, for example NATS outside this release, a+ # private object-store or upstream endpoint, an egress proxy, or the+ # node-local endpoint that workload identity reads credentials from.+ # Each entry needs a non-empty `to` (scoped selectors, or an ipBlock with+ # a prefix length above /0) and `ports` (each with a port, and no range+ # wider than 60000 ports).+ extraEgress: []# -- Worker pools (one StatefulSet per enabled queuePool/machineProfile/bundle lane)# Each map entry creates a WorkerGroup family: one StatefulSet + one@@ -1167,7 +1213,9 @@ workers:# contains the remote adapters, with the remote bundle; the server image# must ship the remote bundle. It requests only cpu, memory and# ephemeral-storage, sets no runtimeClassName and does not inherit- # workers.common.runtimeClassName. It requires workers.networkPolicy.+ # workers.common.runtimeClassName. It requires workers.networkPolicy or+ # workers.remote.networkPolicy. The former excludes remote lanes when the+ # latter is enabled; otherwise workers.networkPolicy.extraIngress must be empty.remote:enabled: falsediff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.pyindex 015ca52a0..d5cc865c8 100644--- a/tools/ci/tests/test_helm_render.py+++ b/tools/ci/tests/test_helm_render.py@@ -1615,7 +1615,9 @@ def test_remote_lanes_do_not_inherit_the_common_runtime_class(tmp_path: Path) ->def test_the_worker_network_policy_admits_only_the_gateway_to_the_remote_lane(tmp_path: Path) -> None:- docs = rendered_documents(tmp_path, remote_pool_values())+ values = remote_pool_values()+ values["workers"]["remote"] = {"networkPolicy": {"enabled": False}}+ docs = rendered_documents(tmp_path, values)remote_labels = next(doc["spec"]["template"]["metadata"]["labels"]for doc in docs@@ -1632,14 +1634,18 @@ def test_the_worker_network_policy_admits_only_the_gateway_to_the_remote_lane(tmassert peer["podSelector"]["matchLabels"]["app.kubernetes.io/component"] == "gateway"-def test_a_remote_lane_needs_a_worker_network_policy(tmp_path: Path) -> None:- values = remote_pool_values()- values["workers"]["networkPolicy"] = {"enabled": False}+def test_a_remote_lane_needs_one_of_the_two_network_policies(tmp_path: Path) -> None:+ remote_policy_only = remote_pool_values()+ remote_policy_only["workers"]["networkPolicy"] = {"enabled": False}+ neither = remote_pool_values()+ neither["workers"]["networkPolicy"] = {"enabled": False}+ neither["workers"]["remote"] = {"networkPolicy": {"enabled": False}}- result = render_workers(tmp_path, values)+ result = render_workers(tmp_path, neither)+ assert remote_network_policy(rendered_documents(tmp_path, remote_policy_only)) is not Noneassert result.returncode != 0- assert "a remote lane needs workers.networkPolicy.enabled=true" in result.stderr+ assert "a remote lane needs a NetworkPolicy" in result.stderrdef test_a_remote_lane_refuses_extra_ingress_sources(tmp_path: Path) -> None:@@ -1649,6 +1655,7 @@ def test_a_remote_lane_refuses_extra_ingress_sources(tmp_path: Path) -> None:}values = remote_pool_values()values["workers"]["networkPolicy"] = {"enabled": True, "extraIngress": [extra]}+ values["workers"]["remote"] = {"networkPolicy": {"enabled": False}}result = render_workers(tmp_path, values)@@ -2018,3 +2025,506 @@ def test_an_image_pull_secret_may_hold_a_separate_upstream_key(tmp_path: Path) -result = render_workers(tmp_path, values)assert result.returncode == 0, result.stderr+++REMOTE_NETWORK_POLICY = "sie-sie-cluster-worker-remote"+DENIED_BASE_V4 = [+ "10.0.0.0/8",+ "172.16.0.0/12",+ "192.168.0.0/16",+ "100.64.0.0/10",+ "169.254.0.0/16",+ "168.63.129.16/32",+]+DENIED_BASE_V6 = ["fc00::/7", "fe80::/10", "64:ff9b::/96", "64:ff9b:1::/48"]+CLUSTER_DNS = {+ "namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "kube-system"}},+ "podSelector": {"matchLabels": {"k8s-app": "kube-dns"}},+}+++def remote_network_policy(docs: list[dict]) -> dict | None:+ policies = [+ doc for doc in docs if doc["kind"] == "NetworkPolicy" and doc["metadata"]["name"] == REMOTE_NETWORK_POLICY+ ]+ return policies[0] if policies else None+++def pod_labels(doc: dict) -> dict:+ if doc["kind"] == "Pod":+ return doc["metadata"].get("labels", {})+ return doc["spec"]["template"]["metadata"].get("labels", {})+++def selects(selector: dict, labels: dict) -> bool:+ if any(labels.get(key) != value for key, value in (selector.get("matchLabels") or {}).items()):+ return False+ for expression in selector.get("matchExpressions") or []:+ key, operator = expression["key"], expression["operator"]+ if operator == "In" and labels.get(key) not in expression["values"]:+ return False+ if operator == "NotIn" and key in labels and labels[key] in expression["values"]:+ return False+ if operator == "Exists" and key not in labels:+ return False+ if operator == "DoesNotExist" and key in labels:+ return False+ return True+++def selected_workloads(docs: list[dict], selector: dict) -> set[str]:+ return {doc["metadata"]["name"] for doc, _ in pod_specs(docs) if selects(selector, pod_labels(doc))}+++def public_rule(policy: dict) -> dict:+ (rule,) = [rule for rule in policy["spec"]["egress"] if any("ipBlock" in peer for peer in rule.get("to", []))]+ return rule+++def test_the_remote_network_policy_admits_only_the_gateway_and_selects_only_remote_lanes(tmp_path: Path) -> None:+ docs = rendered_documents(tmp_path, remote_pool_values(l4={"enabled": True}, cpu={"enabled": True}))++ policy = remote_network_policy(docs)++ assert policy is not None+ spec = policy["spec"]+ assert selected_workloads(docs, spec["podSelector"]) == {REMOTE_WORKER[1]}+ assert spec["policyTypes"] == ["Ingress", "Egress"]+ (ingress,) = spec["ingress"]+ (peer,) = ingress["from"]+ assert selected_workloads(docs, peer["podSelector"]) == {"sie-sie-cluster-gateway"}+ assert ingress["ports"] == [{"port": 8080, "protocol": "TCP"}]+++def test_no_other_policy_admits_extra_sources_to_the_remote_lane(tmp_path: Path) -> None:+ extra = {+ "from": [{"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "benchmarks"}}}],+ "ports": [{"port": 8080, "protocol": "TCP"}],+ }+ values = remote_pool_values(l4={"enabled": True})+ values["workers"]["networkPolicy"] = {"enabled": True, "extraIngress": [extra]}+ docs = rendered_documents(tmp_path, values)+ lanes = {doc["metadata"]["name"]: pod_labels(doc) for doc, _ in pod_specs(docs) if doc["kind"] == "StatefulSet"}++ def admitted(lane: str) -> list[dict]:+ return [+ rule+ for doc in docs+ if doc["kind"] == "NetworkPolicy" and selects(doc["spec"]["podSelector"], lanes[lane])+ for rule in doc["spec"].get("ingress", [])+ ]++ remote_rules = admitted(REMOTE_WORKER[1])+ assert [peer for rule in remote_rules for peer in rule["from"]] == [+ {+ "podSelector": {+ "matchLabels": remote_network_policy(docs)["spec"]["ingress"][0]["from"][0]["podSelector"][+ "matchLabels"+ ]+ }+ }+ ]+ assert {+ workload+ for rule in remote_rules+ for peer in rule["from"]+ for workload in selected_workloads(docs, peer["podSelector"])+ } == {"sie-sie-cluster-gateway"}+ assert extra in admitted("sie-sie-cluster-worker-l4-default")+++def test_the_remote_network_policy_limits_egress_to_the_resolver_the_release_and_public_upstream_ports(+ tmp_path: Path,+) -> None:+ docs = rendered_documents(tmp_path, remote_pool_values())++ egress = remote_network_policy(docs)["spec"]["egress"]++ assert egress[0] == {+ "to": [CLUSTER_DNS],+ "ports": [{"port": 53, "protocol": "UDP"}, {"port": 53, "protocol": "TCP"}],+ }+ assert all("to" in rule and rule["ports"] for rule in egress)+ in_release = {+ (workload, port["port"])+ for rule in egress[1:]+ for peer in rule["to"]+ if "podSelector" in peer+ for workload in selected_workloads(docs, peer["podSelector"])+ for port in rule["ports"]+ }+ assert in_release == {+ ("sie-nats", 4222),+ ("sie-sie-cluster-config", 8080),+ ("sie-sie-cluster-gateway", 8080),+ }+ public = public_rule(remote_network_policy(docs))+ assert public["to"] == [+ {"ipBlock": {"cidr": "0.0.0.0/0", "except": DENIED_BASE_V4}},+ {"ipBlock": {"cidr": "::/0", "except": DENIED_BASE_V6}},+ ]+ assert public["ports"] == [{"port": 443, "protocol": "TCP"}, {"port": 3128, "protocol": "TCP"}]+++def test_the_cluster_resolver_is_configurable_and_must_be_scoped(tmp_path: Path) -> None:+ node_local = {"ipBlock": {"cidr": "169.254.20.10/32"}}+ values = remote_pool_values()+ values["workers"]["remote"] = {"networkPolicy": {"dnsTo": [CLUSTER_DNS, node_local]}}+ unscoped = remote_pool_values()+ unscoped["workers"]["remote"] = {"networkPolicy": {"dnsTo": [{"podSelector": {}}]}}+ empty = remote_pool_values()+ empty["workers"]["remote"] = {"networkPolicy": {"dnsTo": []}}++ egress = remote_network_policy(rendered_documents(tmp_path, values))["spec"]["egress"]++ assert egress[0]["to"] == [CLUSTER_DNS, node_local]+ assert "dnsTo[0] admits every destination" in render_error(tmp_path, unscoped)+ assert "dnsTo needs at least one peer" in render_error(tmp_path, empty)+++def test_the_remote_network_policy_admits_the_collector_when_it_runs(tmp_path: Path) -> None:+ values = remote_pool_values()+ values.update(AUTOSCALING_VALUES)++ docs = rendered_documents(tmp_path, values)++ egress = remote_network_policy(docs)["spec"]["egress"]+ collector_rules = [+ rule+ for rule in egress+ for peer in rule.get("to", [])+ if "podSelector" in peer+ and peer["podSelector"]["matchLabels"].get("app.kubernetes.io/component") == "otel-collector"+ ]+ assert [rule["ports"] for rule in collector_rules] == [[{"port": 4327, "protocol": "TCP"}]]+++def test_the_remote_network_policy_admits_bundled_tempo(tmp_path: Path) -> None:+ values = remote_pool_values()+ values["observability"] = {"tracing": {"enabled": True, "tempo": {"install": True}}}++ docs = rendered_documents(tmp_path, values)++ tempo_rules = [+ rule+ for rule in remote_network_policy(docs)["spec"]["egress"]+ for peer in rule.get("to", [])+ if "podSelector" in peer and selected_workloads(docs, peer["podSelector"]) == {"tempo"}+ ]+ assert [rule["ports"] for rule in tempo_rules] == [[{"port": 4317, "protocol": "TCP"}]]+++def test_upstream_ports_are_the_explicit_ports_of_what_the_lane_connects_to(tmp_path: Path) -> None:+ values = remote_pool_values()+ values["upstreams"] = {+ "tls-port": upstream(base_url="https://sie.example.internal:8443/v1"),+ "default-port": upstream(base_url="https://host.example.com"),+ "loopback": upstream(base_url="http://127.0.0.1:9000"),+ "loopback-name": upstream(base_url="http://LOCALHOST:9100"),+ "ipv6": upstream(base_url="https://[2001:db8::1]:9443"),+ "proxied": upstream(base_url="https://behind.example.com:7443", proxy_url="http://proxy.example.internal:3128"),+ "proxy-no-port": upstream(base_url="https://other.example.com:6443", proxy_url="http://proxy.example.internal"),+ }++ public = public_rule(remote_network_policy(rendered_documents(tmp_path, values)))++ assert sorted(port["port"] for port in public["ports"]) == [443, 3128, 8443, 9443]+++def test_allowed_ranges_carry_the_denied_ranges_inside_them(tmp_path: Path) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {+ "networkPolicy": {+ "allowedCidrs": ["0.0.0.0/1", "128.0.0.0/1", "203.0.113.0/24", "::/0"],+ "extraDeniedCidrs": ["198.18.0.0/15", "2001:db8:1::/48"],+ }+ }++ public = public_rule(remote_network_policy(rendered_documents(tmp_path, values)))++ assert public["to"] == [+ {"ipBlock": {"cidr": "0.0.0.0/1", "except": ["10.0.0.0/8", "100.64.0.0/10"]}},+ {+ "ipBlock": {+ "cidr": "128.0.0.0/1",+ "except": ["172.16.0.0/12", "192.168.0.0/16", "169.254.0.0/16", "168.63.129.16/32", "198.18.0.0/15"],+ }+ },+ {"ipBlock": {"cidr": "203.0.113.0/24"}},+ {"ipBlock": {"cidr": "::/0", "except": [*DENIED_BASE_V6, "2001:db8:1::/48"]}},+ ]+++def test_an_empty_allowed_list_renders_no_public_rule(tmp_path: Path) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {"networkPolicy": {"allowedCidrs": []}}++ egress = remote_network_policy(rendered_documents(tmp_path, values))["spec"]["egress"]++ assert not [peer for rule in egress for peer in rule.get("to", []) if "ipBlock" in peer]+++def test_an_extra_egress_port_range_set_on_the_command_line_renders(tmp_path: Path) -> None:+ values_file = tmp_path / "values.yaml"+ values_file.write_text(yaml.safe_dump(remote_pool_values()), encoding="utf-8")+ rule = "workers.remote.networkPolicy.extraEgress[0]"++ result = subprocess.run(+ [+ "mise",+ "exec",+ "--",+ "helm",+ "template",+ "sie",+ str(helm.CHART_DIR),+ "--namespace",+ "sie",+ "-f",+ str(values_file),+ "--set",+ f"{rule}.to[0].ipBlock.cidr=203.0.113.7/32",+ "--set",+ f"{rule}.ports[0].port=8000",+ "--set",+ f"{rule}.ports[0].endPort=9000",+ ],+ cwd=ROOT,+ capture_output=True,+ text=True,+ check=False,+ )++ assert result.returncode == 0, result.stderr+ (policy,) = [+ doc+ for doc in yaml.safe_load_all(result.stdout)+ if doc and doc["kind"] == "NetworkPolicy" and doc["metadata"]["name"] == REMOTE_NETWORK_POLICY+ ]+ assert policy["spec"]["egress"][-1]["ports"] == [{"port": 8000, "endPort": 9000}]+++def test_extra_egress_rules_are_appended(tmp_path: Path) -> None:+ rule = {"to": [{"ipBlock": {"cidr": "169.254.169.254/32"}}], "ports": [{"port": 80, "protocol": "TCP"}]}+ values = remote_pool_values()+ values["workers"]["remote"] = {"networkPolicy": {"extraEgress": [rule]}}++ egress = remote_network_policy(rendered_documents(tmp_path, values))["spec"]["egress"]++ assert egress[-1] == rule+++ ("network_policy", "message"),+ [+ ({"extraEgress": [{"ports": [{"port": 443}]}]}, "extraEgress[0] needs a non-empty to and ports"),+ (+ {"extraEgress": [{"to": [{"ipBlock": {"cidr": "10.0.0.1/32"}}]}]},+ "extraEgress[0] needs a non-empty to and ports",+ ),+ ({"extraEgress": [{"to": [{}], "ports": [{"port": 443}]}]}, "extraEgress[0].to[0] admits every destination"),+ (+ {"extraEgress": [{"to": [{"podSelector": {}}], "ports": [{"port": 443}]}]},+ "extraEgress[0].to[0] admits every destination",+ ),+ (+ {"extraEgress": [{"to": [{"ipBlock": {"cidr": "0.0.0.0/0"}}], "ports": [{"port": 443}]}]},+ "extraEgress[0].to[0] admits every address",+ ),+ (+ {"extraEgress": [{"to": [{"ipBlock": {"cidr": "10.0.0.1/32"}}], "ports": [{}]}]},+ "extraEgress[0].ports[0] admits every port",+ ),+ (+ {"extraEgress": [{"to": [{"ipBlock": {"cidr": "10.0.0.1/32"}}], "ports": [{"port": 1, "endPort": 65535}]}]},+ "extraEgress[0].ports[0] spans nearly every port",+ ),+ (+ {+ "extraEgress": [+ {"to": [{"ipBlock": {"cidr": "10.0.0.1/32"}}], "ports": [{"port": "https", "endPort": 9000}]}+ ]+ },+ "extraEgress[0].ports[0] sets endPort, which needs a numeric port",+ ),+ (+ {+ "extraEgress": [+ {"to": [{"ipBlock": {"cidr": "10.0.0.1/32"}}], "ports": [{"port": 8000, "endPort": "9000"}]}+ ]+ },+ "extraEgress[0].ports[0].endPort must be an integer",+ ),+ ({"allowedCidrs": ["2000::/3"]}, "allowedCidrs[0]: the only IPv6 entry is ::/0"),+ ({"allowedCidrs": ["10.1.0.0/16"]}, "allowedCidrs[0] lies inside the denied range 10.0.0.0/8"),+ ({"allowedCidrs": ["0.0.0.0/33"]}, "allowedCidrs[0] must be an IPv4 CIDR"),+ ({"extraDeniedCidrs": ["not-a-range"]}, "extraDeniedCidrs[0] must be a CIDR"),+ ],+)+def test_unsafe_remote_network_policy_values_fail_the_render(+ tmp_path: Path, network_policy: dict, message: str+) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {"networkPolicy": network_policy}++ assert message in render_error(tmp_path, values)+++ "values",+ [+ {"upstreams": {"team": upstream()}, **L4_POOL},+ {+ "workers": {+ "networkPolicy": {"enabled": True},+ "remote": {"networkPolicy": {"enabled": False}},+ "pools": {"remote": {"enabled": True}},+ }+ },+ ],+ ids=["no-remote-lane", "disabled"],+)+def test_no_remote_network_policy_without_a_remote_lane_or_when_disabled(tmp_path: Path, values: dict) -> None:+ assert remote_network_policy(rendered_documents(tmp_path, values)) is None+++INVALID_POLICY_CIDRS = [+ "2001:db8::/129",+ "2001:db8::/999",+ "2001:::1/64",+ "2001:db8::1::2/64",+ "1:2:3:4:5:6:7:8:9/64",+ "1:2:3:4:5:6:7/64",+ "::ffff:999.2.3.4/128",+ "999.2.3.4/32",+ "10.0.0.0/33",+]++[email protected]("cidr", INVALID_POLICY_CIDRS)[email protected]("surface", ["extraDeniedCidrs", "extraEgress"])+def test_remote_policy_rejects_invalid_cidrs(tmp_path: Path, cidr: str, surface: str) -> None:+ values = remote_pool_values()+ policy = (+ {"extraDeniedCidrs": [cidr]}+ if surface == "extraDeniedCidrs"+ else {"extraEgress": [{"to": [{"ipBlock": {"cidr": cidr}}], "ports": [{"port": 443}]}]}+ )+ values["workers"]["remote"] = {"networkPolicy": policy}++ result = render_workers(tmp_path, values)++ assert result.returncode != 0+ assert surface in result.stderr+ assert "CIDR" in result.stderr++[email protected]("cidr", ["::/128", "2001:db8::/64", "1:2:3:4:5:6:7:8/128", "2001:db8::192.0.2.1/128"])+def test_remote_policy_accepts_valid_ipv6_cidrs(tmp_path: Path, cidr: str) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {+ "networkPolicy": {+ "extraDeniedCidrs": [cidr],+ "extraEgress": [{"to": [{"ipBlock": {"cidr": cidr}}], "ports": [{"port": 443}]}],+ }+ }++ result = render_workers(tmp_path, values)++ assert result.returncode == 0, result.stderr+++ "policy",+ [+ {"allowedCidrs": ["10.0.0.0/8"]},+ {"allowedCidrs": ["10.1.2.3/8"]},+ {"extraDeniedCidrs": ["0.0.0.0/0"]},+ {"extraDeniedCidrs": ["::/0"]},+ {"extraDeniedCidrs": ["0:0:0:0:0:0:0:0/0"]},+ {"allowedCidrs": ["192.0.2.0/24"], "extraDeniedCidrs": ["192.0.2.32/24"]},+ ],+)+def test_remote_policy_rejects_an_allowed_range_covered_by_a_denial(tmp_path: Path, policy: dict) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {"networkPolicy": policy}+ result = render_workers(tmp_path, values)+ assert result.returncode != 0+ assert re.search(r"lies inside the denied range|CIDR with a network address", result.stderr)+++ "cidr",+ [+ "::ffff:192.0.2.1/128",+ "::ffff:c000:201/128",+ "0:0:0:0:0:FFFF:C000:0201/128",+ "203.0.113.1/24",+ "2001:db8::1/64",+ ],+)[email protected]("surface", ["extraDeniedCidrs", "extraEgress"])+def test_remote_policy_rejects_mapped_addresses_and_host_bits(tmp_path: Path, cidr: str, surface: str) -> None:+ values = remote_pool_values()+ policy = (+ {"extraDeniedCidrs": [cidr]}+ if surface == "extraDeniedCidrs"+ else {"extraEgress": [{"to": [{"ipBlock": {"cidr": cidr}}], "ports": [{"port": 443}]}]}+ )+ values["workers"]["remote"] = {"networkPolicy": policy}+ result = render_workers(tmp_path, values)+ assert result.returncode != 0+ assert surface in result.stderr+ assert "CIDR" in result.stderr+++ "peer",+ [+ {"ipBlock": {"cidr": "203.0.113.0/24"}, "podSelector": {"matchLabels": {"app": "proxy"}}},+ {"ipBlock": {"cidr": "203.0.113.0/24"}, "namespaceSelector": {"matchLabels": {"name": "proxy"}}},+ ],+)+def test_remote_policy_rejects_ipblock_mixed_with_selectors(tmp_path: Path, peer: dict) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {"networkPolicy": {"extraEgress": [{"to": [peer], "ports": [{"port": 443}]}]}}+ assert "cannot combine ipBlock" in render_error(tmp_path, values)+++ "port",+ [+ {"port": -1},+ {"port": 65536},+ {"port": 443.5},+ {"port": 443, "endPort": 0},+ {"port": 443, "endPort": 65536},+ {"port": 443, "endPort": 442},+ ],+)+def test_remote_policy_rejects_invalid_numeric_ports(tmp_path: Path, port: dict) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {+ "networkPolicy": {"extraEgress": [{"to": [{"ipBlock": {"cidr": "203.0.113.0/24"}}], "ports": [port]}]}+ }+ assert "extraEgress[0].ports[0]" in render_error(tmp_path, values)+++def test_remote_policy_accepts_combined_selectors_and_a_named_port(tmp_path: Path) -> None:+ values = remote_pool_values()+ values["workers"]["remote"] = {+ "networkPolicy": {+ "extraEgress": [+ {+ "to": [+ {+ "podSelector": {"matchLabels": {"app": "proxy"}},+ "namespaceSelector": {"matchLabels": {"name": "proxy"}},+ }+ ],+ "ports": [{"port": "https"}],+ }+ ]+ }+ }+ assert render_workers(tmp_path, values).returncode == 0