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
fix(helm)!: require authenticated, TLS-protected gateway exposure and bound the pool API (#393)
Krisztian Gajdarbc2e66a2aad6
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 7bbf3df90..1f098baa7 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -755,7 +755,8 @@ fail-closed isolation behavior.`values-ha.yaml` is the tested composition of the durability knobs below witha replicated broker and a second gateway: two gateway replicas, a three-memberNATS cluster with a JetStream file store per member, and file-backed work-queue-streams replicated across all three. Layer it under a provider overlay:+streams replicated across all three. It also enables the+[worker NetworkPolicy](#worker-networkpolicy). Layer it under a provider overlay:```bashhelm install sie deploy/helm/sie-cluster \@@ -1118,25 +1119,172 @@ contain the generated tokens.## Ingress-Enable the Ingress with `ingress.enabled=true` and route traffic to the gateway by-hostname. Use the list-valued `ingress.hosts` to front the gateway with one or more-hostnames — each entry becomes an Ingress rule (and, when TLS is enabled, a SAN on-the cert):+The Ingress is off by default, including in the AWS, GKE, AKS, and ACK+overlays. Install an ingress controller first, then enable it with+`ingress.enabled=true`, gateway auth, and TLS, and route traffic to the gateway+by hostname. Use the list-valued `ingress.hosts` to front the gateway with one+or more hostnames — each entry becomes an Ingress rule (and, when TLS is+enabled, a SAN on the cert):```yaml+gateway:+ auth:+ mode: static+ tokenSecretName: sie-gateway-auth # Secret with comma-separated tokensingress:enabled: trueclassName: nginxhosts:- sie.example.com- api.example.com+ tlsConfig:+ enabled: true```+With the default `byo` TLS mode, create the `kubernetes.io/tls` Secret named by+`ingress.tlsConfig.secretName` (default `sie-tls`) before installing, or use the+`cert-manager` or `self-signed` mode described in [TLS / HTTPS](#tls--https).+The singular `ingress.host` is the backward-compatible single-host shorthand; it isignored whenever `ingress.hosts` is non-empty. With neither set the chart renders ahost-less catch-all Ingress. All hosts share the single `ingress.tlsConfig.secretName`(one multi-SAN certificate).+### Authentication and TLS requirements++The gateway authenticates nothing by default (`gateway.auth.mode: none`). The+chart refuses to render a gateway Ingress unless something authenticates its+requests, because an Ingress publishes the inference API and the pool API,+which keeps GPU workers warm, to anyone who can reach the ingress controller.+A hostname or a certificate is not access control: hostnames are public DNS and+certificates appear in Certificate Transparency logs. One of the following must+hold:++- the gateway requires a token: `gateway.auth.mode=static` with+ `gateway.auth.tokenSecretName` naming a Secret of comma-separated tokens.+ SDK clients pass one as `api_key`/`apiKey`, or read it from `SIE_API_KEY`+ when their base URL comes from `SIE_BASE_URL`;+- the oauth2-proxy edge is enabled (`auth.enabled=true`). It works through the+ `nginx.ingress.kubernetes.io/auth-*` annotations, which only the ingress-nginx+ controller honours; the NGINX Inc controller (`nginx.org/ingress-controller`)+ ignores them even when its class is also named `nginx`. With cluster access+ (`helm install`/`upgrade`), the chart looks up the IngressClass named by+ `ingress.className` and requires its `spec.controller` to be listed in+ `auth.ingress.acceptedControllers` (default `k8s.io/ingress-nginx`; add the+ controller string of a second ingress-nginx installation, for example+ `k8s.io/internal-ingress-nginx`). When `ingress.className` is empty, the API+ server assigns one of the default IngressClasses, so every class marked as+ default must use an accepted controller. An offline render+ (`helm template`, including GitOps tools that render that way) cannot see+ IngressClasses, so it accepts only `ingress.className=nginx` and cannot tell+ the two controllers apart; use gateway token auth there if the class name+ differs. The default `auth.oauth2Proxy.emailDomain: "*"` admits any account+ the configured OIDC issuer authenticates; narrow it for a shared issuer;+- `ingress.allowUnauthenticated=true` explicitly accepts an unauthenticated+ Ingress, for example behind a private ingress controller.++The Ingress also needs TLS, so tokens and session cookies do not cross the+network in cleartext: `ingress.tlsConfig.enabled=true` with at least one host+(the Ingress carries TLS only for named hosts, so an IP-only self-signed+certificate from `selfSigned.leaf.ipAddresses` is not supported for the gateway+Ingress), `ingress.tlsConfig.mode=disabled` as an explicit statement that TLS+terminates upstream of the Ingress, or the explicit `ingress.allowPlaintext=true`.+The MCP edge Ingress (`mcpEdge.ingress`) carries connector secrets and OAuth+tokens and follows the same TLS rule, with `mcpEdge.ingress.allowPlaintext=true`+as its explicit opt-in. Its certificate lives in its own Secret,+`<release fullname>-mcp-tls`: `cert-manager` mode issues it, `byo` mode expects+you to create it, and `self-signed` mode does not issue it, so the chart refuses+`self-signed` with the MCP edge Ingress.++Both opt-ins accept only a YAML boolean; a quoted `"false"` fails the render.+`gateway.auth.mode` must be `none`, `static`, or `token` exactly as the gateway+reads it, and token auth without `gateway.auth.tokenSecretName` (or a+`SIE_AUTH_TOKEN(S)` entry in `gateway.extraEnv`) fails the render because the+gateway would refuse every request. `gateway.auth.tokenSecretName` with auth+mode `none` fails for the same reason. A `gateway.extraEnv` entry that overrides+`SIE_AUTH_MODE` takes precedence over `gateway.auth.mode`.++The same authentication requirement applies to `gateway.service.type:+LoadBalancer` or `NodePort`, which are reachable from outside the cluster on+most managed platforms; `gateway.service.allowUnauthenticated=true` is the+explicit opt-in there. Because the gateway itself serves plain HTTP, those+Service types also need `gateway.service.allowPlaintext=true`: configure TLS+termination through your provider's load-balancer annotations in+`gateway.service.annotations` where available, or prefer an Ingress with TLS. `config.service.type` must stay `ClusterIP`: sie-config+is the configuration write authority and accepts unauthenticated writes unless+an admin token is configured.++With gateway token auth, pool create, renew, and delete also require the+gateway admin token (see [Gateway admin token](#gateway-admin-token)).+Independently of auth, the gateway bounds API-created pools:++- the warm floor (`minimum_worker_count`, which applies to each of the pool's+ machine profiles) and the `gpus` requirement may each add up to at most 4+ workers per pool by default, and a pool's active lease keeps at most its+ requirement warm;+- the lease TTL is capped at 3600 s by default;+- live API-created pools are capped at 64 by default. Each gateway replica+ checks the pools it knows, including ones replicated from other replicas,+ so concurrent creates on different replicas can briefly exceed the cap; it+ is not a strict cluster-wide limit.++Tune them with `SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT`,+`SIE_GATEWAY_POOL_MAX_TTL_S`, and `SIE_GATEWAY_MAX_POOLS` in `gateway.extraEnv`.++> **Upgrade note (breaking):** `values-aws.yaml`, `values-gke.yaml`, and+> `values-aks.yaml` used to enable a host-less, TLS-less Ingress in front of an+> unauthenticated gateway. Upgrading with those overlays now removes that+> Ingress, and the install notes warn when that happens. To keep external+> access, set `ingress.enabled=true` with gateway auth and TLS as above. To keep+> the previous unauthenticated plain-HTTP catch-all Ingress unchanged, set both+> `ingress.allowUnauthenticated=true` and `ingress.allowPlaintext=true`. An+> upgrade with `--reuse-values` keeps `ingress.enabled=true` and fails the+> render until one of these is chosen. An existing Ingress with gateway auth+> but no TLS needs TLS or `ingress.allowPlaintext=true`.+>+> API-created pools stored before the upgrade keep working but are held to+> the new per-pool budget: a pool whose `gpus` requirements add up to more than+> `SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT` is allotted the budget in+> machine-profile name order, becomes Active once the allotted workers are+> available, and keeps only those warm; a warm floor that no longer fits is+> spread over its lanes (at least one worker each on as many lanes as the budget+> allows). Recreate such a pool within the budget, or raise the budget.++### Worker NetworkPolicy++Worker pods serve an HTTP API without authentication of their own; the gateway+is the only in-chart caller. `workers.networkPolicy.enabled=true` renders an+ingress `NetworkPolicy` whose only default rule admits this release's gateway+pods to every worker HTTP port. Kubelet probes and traffic between containers+of the same pod are unaffected. It requires a CNI that enforces NetworkPolicy.+NetworkPolicies are additive: if another policy selects the worker pods and+admits more sources, those sources keep access, so it restricts worker ingress+only when no other policy grants broader access. Check for overlapping policies+in the namespace. It is off by default and on in `values-ha.yaml`. Add+`workers.networkPolicy.extraIngress` rules for any caller outside the chart that+must reach workers directly, and list the worker ports (`workers.common.port`,+plus one port per additional child container on multi-GPU pools) so the rule+does not open every port on the worker pods. The chart rejects rules that admit+every source (an empty peer, an unscoped selector, or an `ipBlock` with prefix+length `/0`) or nearly every port (a port entry without `port`, or a range+wider than 60000 ports); disable the policy instead to open the worker API to+everything. These checks catch mistakes, not a determined operator: two `/1`+halves still admit every address.++```yaml+workers:+ networkPolicy:+ enabled: true+ extraIngress:+ - from:+ - namespaceSelector:+ matchLabels:+ kubernetes.io/metadata.name: benchmarks+ ports:+ - port: 8080+ protocol: TCP+```+## TLS / HTTPSThe chart supports four TLS modes for the Ingress (set via `ingress.tlsConfig.mode`):diff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txtindex ac7b6cdc0..009018c01 100644--- a/deploy/helm/sie-cluster/templates/NOTES.txt+++ b/deploy/helm/sie-cluster/templates/NOTES.txt@@ -24,6 +24,12 @@ Grafana password: kubectl get secret -n {{ include "sie-cluster.kubePrometheusSt{{- if .Values.keda.install }}KEDA: enabled{{- 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" . }} because+ingress.enabled is false (the cloud overlays no longer enable it). To keep external access, set+ingress.enabled=true with gateway auth and TLS; see the chart README section "Ingress".+{{- end }}{{- if and $tls.enabled (eq (default "byo" $tls.mode) "cert-manager") }}TLS via cert-manager: certificate is being issued via ACME HTTP-01 challenge.diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex f181e394e..99b2796b5 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -819,6 +819,211 @@ Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or{{- end }}{{- end }}+{{/*+Strict boolean opt-in: only a YAML boolean true enables it. Any other non-null+value fails the render so a quoted "false" can never read as true.+Args (dict): value, path.+*/}}+{{- define "sie-cluster.optIn" -}}+{{- $value := .value -}}+{{- if not (or (kindIs "invalid" $value) (kindIs "bool" $value)) -}}+{{- fail (printf "%s must be a boolean (true or false), got %q" .path (toString $value)) -}}+{{- end -}}+{{- if and (kindIs "bool" $value) $value -}}true{{- end -}}+{{- end }}++{{/*+The SIE_AUTH_MODE the gateway container receives, as JSON {"mode", "known"}.+gateway.auth.mode is passed verbatim; a later gateway.extraEnv entry named+SIE_AUTH_MODE replaces it. An override without a literal value (valueFrom) is+not known at render time.+*/}}+{{- define "sie-cluster.gateway.effectiveAuthMode" -}}+{{- $gateway := default (dict) .Values.gateway -}}+{{- $mode := toString (dig "auth" "mode" "none" $gateway) -}}+{{- $known := true -}}+{{- range $entry := (default (list) $gateway.extraEnv) -}}+{{- if and (kindIs "map" $entry) (eq (toString (index $entry "name")) "SIE_AUTH_MODE") -}}+{{- if hasKey $entry "value" -}}+{{- $mode = toString (index $entry "value") -}}+{{- $known = true -}}+{{- else -}}+{{- $mode = "" -}}+{{- $known = false -}}+{{- end -}}+{{- end -}}+{{- end -}}+{{- dict "mode" $mode "known" $known | toJson -}}+{{- end }}++{{/*+"true" when the gateway enforces token auth: the effective SIE_AUTH_MODE is+known and is exactly static or token, the values the gateway accepts.+*/}}+{{- define "sie-cluster.gateway.authenticates" -}}+{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}+{{- if and $auth.known (has $auth.mode (list "static" "token")) -}}true{{- end -}}+{{- end }}++{{/*+Validation: gateway auth values. The gateway accepts exactly none, "", static,+and token, and refuses every request when token auth has no token.+*/}}+{{- define "sie-cluster.validateGatewayAuth" -}}+{{- $gateway := default (dict) .Values.gateway -}}+{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}+{{- if $auth.known -}}+{{- if not (has $auth.mode (list "none" "" "static" "token")) -}}+{{- fail (printf "gateway auth mode %q is not supported; set gateway.auth.mode (or a gateway.extraEnv SIE_AUTH_MODE override) to none, static, or token." $auth.mode) -}}+{{- end -}}+{{- if has $auth.mode (list "static" "token") -}}+{{- $tokenSource := dig "auth" "tokenSecretName" "" $gateway -}}+{{- range $entry := (default (list) $gateway.extraEnv) -}}+{{- if and (kindIs "map" $entry) (has (toString (index $entry "name")) (list "SIE_AUTH_TOKEN" "SIE_AUTH_TOKENS")) -}}+{{- $tokenSource = "extraEnv" -}}+{{- end -}}+{{- end -}}+{{- if not $tokenSource -}}+{{- fail (printf "gateway auth mode %q needs tokens: set gateway.auth.tokenSecretName to a Secret holding comma-separated tokens, or the gateway refuses every request." $auth.mode) -}}+{{- end -}}+{{- else if dig "auth" "tokenSecretName" "" $gateway -}}+{{- fail "gateway.auth.tokenSecretName is set but gateway auth mode is none: the gateway treats tokens without token auth as a misconfiguration and refuses every request with 500. Set gateway.auth.mode=static to enforce the tokens, or clear gateway.auth.tokenSecretName." -}}+{{- end -}}+{{- end -}}+{{- end }}++{{/*+Validation: the oauth2-proxy edge (auth.enabled) is enforced only by an+ingress-nginx controller, which honours the nginx.ingress.kubernetes.io/auth-*+annotations; auth.ingress.acceptedControllers lists the IngressClass+spec.controller values that count (default k8s.io/ingress-nginx). With cluster+access the chart looks up the IngressClass named by ingress.className. When it+is empty, the API server assigns one of the classes marked as default, so every+default class must use an accepted controller. An offline render (helm+template) cannot see IngressClasses and cannot tell ingress-nginx from other+controllers that also use the class name nginx, so it accepts only+ingress.className=nginx.+*/}}+{{- define "sie-cluster.validateOauth2EdgeController" -}}+{{- $className := toString (default "" .Values.ingress.className) -}}+{{- $accepted := list -}}+{{- range $controller := (default (list "k8s.io/ingress-nginx") (dig "ingress" "acceptedControllers" nil (default (dict) .Values.auth))) -}}+{{- $accepted = append $accepted (toString $controller) -}}+{{- end -}}+{{- $classes := lookup "networking.k8s.io/v1" "IngressClass" "" "" -}}+{{- $items := list -}}+{{- if $classes -}}+{{- $items = default (list) $classes.items -}}+{{- end -}}+{{- if $items -}}+{{- $candidates := list -}}+{{- range $class := $items -}}+{{- $metadata := default (dict) $class.metadata -}}+{{- $annotations := default (dict) $metadata.annotations -}}+{{- if $className -}}+{{- if eq (toString $metadata.name) $className -}}+{{- $candidates = append $candidates $class -}}+{{- end -}}+{{- else if eq (toString (index $annotations "ingressclass.kubernetes.io/is-default-class")) "true" -}}+{{- $candidates = append $candidates $class -}}+{{- end -}}+{{- end -}}+{{- if not $candidates -}}+{{- if $className -}}+{{- fail (printf "auth.enabled=true needs an ingress-nginx IngressClass for the gateway Ingress, but no IngressClass named %q exists in the cluster." $className) -}}+{{- end -}}+{{- fail "auth.enabled=true needs an ingress-nginx IngressClass for the gateway Ingress, but ingress.className is empty and no IngressClass is marked as the cluster default." -}}+{{- end -}}+{{- range $class := $candidates -}}+{{- $controller := toString (dig "spec" "controller" "" $class) -}}+{{- if not (has $controller $accepted) -}}+{{- fail (printf "auth.enabled=true puts the oauth2-proxy edge in front of the gateway through ingress-nginx auth annotations, but IngressClass %q%s uses controller %q, which is not in auth.ingress.acceptedControllers %v; other controllers, such as the NGINX Inc controller (nginx.org/ingress-controller), ignore those annotations, so the gateway would be published without that check. Use an ingress-nginx IngressClass, add its controller to auth.ingress.acceptedControllers, or enable gateway auth (gateway.auth.mode=static) and set auth.enabled=false." (toString (dig "metadata" "name" "" $class)) (ternary "" " (a default IngressClass, which the API server may assign to the Ingress)" (ne $className "")) $controller $accepted) -}}+{{- end -}}+{{- end -}}+{{- else if ne $className "nginx" -}}+{{- fail (printf "auth.enabled=true puts the oauth2-proxy edge in front of the gateway through ingress-nginx auth annotations. This render cannot inspect IngressClasses (for example helm template), so it accepts only ingress.className=nginx and cannot verify the controller behind %q. Use ingress.className=nginx with ingress-nginx, install with cluster access so the chart can check the IngressClass controller, or enable gateway auth (gateway.auth.mode=static) and set auth.enabled=false." $className) -}}+{{- end -}}+{{- end }}++{{/*+Validation: a gateway Ingress needs authentication and TLS.+Authentication is gateway token auth, the oauth2-proxy edge (auth.enabled,+enforced through ingress-nginx annotations; see+sie-cluster.validateOauth2EdgeController), or the explicit+ingress.allowUnauthenticated opt-in. A hostname is not access+control. TLS is ingress.tlsConfig.enabled with at least one host (the chart+renders no TLS block without one), ingress.tlsConfig.mode=disabled as an+explicit statement that TLS terminates upstream, or the explicit+ingress.allowPlaintext opt-in.+*/}}+{{- define "sie-cluster.validateIngressExposure" -}}+{{- if .Values.ingress.enabled -}}+{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" .Values.ingress.allowUnauthenticated "path" "ingress.allowUnauthenticated") -}}+{{- $allowPlaintext := include "sie-cluster.optIn" (dict "value" .Values.ingress.allowPlaintext "path" "ingress.allowPlaintext") -}}+{{- $edgeAuth := dig "enabled" false (default (dict) .Values.auth) -}}+{{- if $edgeAuth -}}+{{- include "sie-cluster.validateOauth2EdgeController" . -}}+{{- end -}}+{{- $gatewayAuth := include "sie-cluster.gateway.authenticates" . -}}+{{- if not (or $gatewayAuth $edgeAuth $allowUnauthenticated) -}}+{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}+{{- fail (printf "Refusing to render the gateway Ingress: nothing authenticates its requests (effective SIE_AUTH_MODE=%q, auth.enabled=false), so it would publish the inference and pool APIs to anyone who can reach the ingress controller. A hostname or TLS is not access control. Enable gateway auth (gateway.auth.mode=static with gateway.auth.tokenSecretName) or the oauth2-proxy edge (auth.enabled=true with ingress-nginx), or set ingress.allowUnauthenticated=true to publish it without authentication." $auth.mode) -}}+{{- end -}}+{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray -}}+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml -}}+{{- $upstreamTls := eq (toString (default "byo" $tls.mode)) "disabled" -}}+{{- $ingressTls := and $tls.enabled (gt (len $hosts) 0) -}}+{{- if not (or $upstreamTls $ingressTls $allowPlaintext) -}}+{{- fail "Refusing to render the gateway Ingress without TLS: tokens and session cookies would cross the network in plaintext. Set ingress.hosts with ingress.tlsConfig.enabled=true (the Ingress carries TLS only for named hosts, so an IP-only self-signed certificate is not supported for the gateway Ingress), set ingress.tlsConfig.mode=disabled when TLS terminates upstream of the Ingress, or set ingress.allowPlaintext=true to serve plain HTTP." -}}+{{- end -}}+{{- end -}}+{{- end }}++{{/*+Validation: the MCP edge Ingress carries connector secrets and OAuth tokens,+so it needs TLS (ingress.tlsConfig.enabled, or mode=disabled when TLS+terminates upstream) or the explicit mcpEdge.ingress.allowPlaintext opt-in.+*/}}+{{- define "sie-cluster.validateMcpEdgeIngressTls" -}}+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml -}}+{{- $upstreamTls := eq (toString (default "byo" $tls.mode)) "disabled" -}}+{{- $allowPlaintext := include "sie-cluster.optIn" (dict "value" (dig "ingress" "allowPlaintext" nil (default (dict) .Values.mcpEdge)) "path" "mcpEdge.ingress.allowPlaintext") -}}+{{- if not (or $tls.enabled $upstreamTls $allowPlaintext) -}}+{{- fail "Refusing to render the MCP edge Ingress without TLS: it carries connector secrets and OAuth tokens. Set ingress.tlsConfig.enabled=true, set ingress.tlsConfig.mode=disabled when TLS terminates upstream of the Ingress, or set mcpEdge.ingress.allowPlaintext=true to serve plain HTTP." -}}+{{- end -}}+{{- if and $tls.enabled (eq (toString $tls.mode) "self-signed") -}}+{{- fail (printf "ingress.tlsConfig.mode=self-signed issues its certificate into %q for the gateway hosts only; nothing issues the MCP edge certificate (Secret %q) for mcpEdge.ingress.host. Use ingress.tlsConfig.mode=cert-manager, or mode=byo with that Secret created, or mode=disabled when TLS terminates upstream of the Ingress." (toString $tls.secretName) (printf "%s-tls" (include "sie-cluster.mcpEdge.serviceName" .))) -}}+{{- end -}}+{{- end }}++{{/*+Validation: a gateway Service of type LoadBalancer or NodePort is reachable+from outside the cluster on most managed Kubernetes platforms, so it needs+gateway token auth or the explicit gateway.service.allowUnauthenticated+opt-in, and, because the gateway serves plain HTTP, the explicit+gateway.service.allowPlaintext acknowledgement. sie-config accepts unauthenticated writes unless an admin token is+configured (outside a production deployment environment), so its Service+stays ClusterIP.+*/}}+{{- define "sie-cluster.validateServiceExposure" -}}+{{- $serviceType := toString (dig "service" "type" "ClusterIP" (default (dict) .Values.gateway)) -}}+{{- if has $serviceType (list "LoadBalancer" "NodePort") -}}+{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" (dig "service" "allowUnauthenticated" nil (default (dict) .Values.gateway)) "path" "gateway.service.allowUnauthenticated") -}}+{{- if not (or (include "sie-cluster.gateway.authenticates" .) $allowUnauthenticated) -}}+{{- fail (printf "Refusing to render gateway.service.type=%s without gateway auth: the Service is reachable from outside the cluster on most managed platforms and would publish the inference and pool APIs. Enable gateway auth (gateway.auth.mode=static with gateway.auth.tokenSecretName), or set gateway.service.allowUnauthenticated=true." $serviceType) -}}+{{- end -}}+{{- $allowPlaintext := include "sie-cluster.optIn" (dict "value" (dig "service" "allowPlaintext" nil (default (dict) .Values.gateway)) "path" "gateway.service.allowPlaintext") -}}+{{- if not $allowPlaintext -}}+{{- fail (printf "Refusing to render gateway.service.type=%s without an explicit TLS decision: the gateway serves plain HTTP, so tokens would cross the network in cleartext unless the load balancer terminates TLS. Prefer an Ingress with TLS, or configure TLS termination through provider annotations in gateway.service.annotations and set gateway.service.allowPlaintext=true to acknowledge that the gateway itself serves HTTP." $serviceType) -}}+{{- end -}}+{{- end -}}+{{- $config := default (dict) .Values.config -}}+{{- $configServiceType := toString (dig "service" "type" "ClusterIP" $config) -}}+{{- if and $config.enabled (ne $configServiceType "ClusterIP") -}}+{{- fail (printf "config.service.type=%s is not supported: sie-config is the configuration write authority and must stay ClusterIP. Reach it in-cluster or through kubectl port-forward." $configServiceType) -}}+{{- end -}}+{{- end }}+{{/*KEDA apply hook: ServiceAccount name*/}}diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex 0b401eca0..8f30ab4d8 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -1,3 +1,4 @@+{{- include "sie-cluster.validateGatewayAuth" . }}{{- /* Validate: at most one static overlay may be active. Zero overlays is thedefault; the gateway fetches bundles+models from sie-config at startupand has NO baked-in filesystem seed (seediff --git a/deploy/helm/sie-cluster/templates/gateway-service.yaml b/deploy/helm/sie-cluster/templates/gateway-service.yamlindex c2fd095d4..d42f4c328 100644--- a/deploy/helm/sie-cluster/templates/gateway-service.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-service.yaml@@ -1,3 +1,4 @@+{{- include "sie-cluster.validateServiceExposure" . }}apiVersion: v1kind: Servicemetadata:diff --git a/deploy/helm/sie-cluster/templates/ingress.yaml b/deploy/helm/sie-cluster/templates/ingress.yamlindex 4063f8a95..89eb0d404 100644--- a/deploy/helm/sie-cluster/templates/ingress.yaml+++ b/deploy/helm/sie-cluster/templates/ingress.yaml@@ -1,4 +1,5 @@{{- if .Values.ingress.enabled }}+{{- include "sie-cluster.validateIngressExposure" . }}{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray }}{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}apiVersion: networking.k8s.io/v1diff --git a/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yamlindex 4b7ec9954..c09dc3ef1 100644--- a/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml+++ b/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml@@ -12,6 +12,7 @@{{- fail (printf "Invalid configuration: mcpEdge.ingress.host (%s) collides with a gateway ingress host; both Ingresses would serve path / on the same hostname. Give the MCP edge a distinct host (e.g. sie-mcp.example.com)." $host) }}{{- end }}{{- end }}+{{- include "sie-cluster.validateMcpEdgeIngressTls" . }}{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}{{- $tlsSecret := printf "%s-tls" (include "sie-cluster.mcpEdge.serviceName" .) }}apiVersion: networking.k8s.io/v1diff --git a/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml b/deploy/helm/sie-cluster/templates/worker-networkpolicy.yamlnew file mode 100644index 000000000..1ef71f3c8--- /dev/null+++ b/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml@@ -0,0 +1,64 @@+{{- $networkPolicy := default (dict) .Values.workers.networkPolicy }}+{{- if $networkPolicy.enabled }}+{{- range $index, $rule := (default (list) $networkPolicy.extraIngress) }}+{{- if not (and (kindIs "map" $rule) $rule.from $rule.ports) }}+{{- fail (printf "workers.networkPolicy.extraIngress[%d] needs a non-empty from and ports: a rule without them admits every source or every port on the worker pods." $index) }}+{{- end }}+{{- range $peerIndex, $peer := $rule.from }}+{{- $scoped := false }}+{{- if kindIs "map" $peer }}+{{- 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 regexMatch "/0+$" (trim $cidr) }}+{{- fail (printf "workers.networkPolicy.extraIngress[%d].from[%d] admits every address (ipBlock %s). To open the worker API to every source, disable workers.networkPolicy instead." $index $peerIndex $cidr) }}+{{- end }}+{{- $scoped = true }}+{{- end }}+{{- end }}+{{- if not $scoped }}+{{- fail (printf "workers.networkPolicy.extraIngress[%d].from[%d] admits every source: give it a podSelector or namespaceSelector with matchLabels or matchExpressions, or an ipBlock." $index $peerIndex) }}+{{- end }}+{{- end }}+{{- range $portIndex, $port := $rule.ports }}+{{- if not (and (kindIs "map" $port) $port.port) }}+{{- fail (printf "workers.networkPolicy.extraIngress[%d].ports[%d] admits every port: set port." $index $portIndex) }}+{{- end }}+{{- if and $port.endPort (not (kindIs "string" $port.port)) (gt (sub (int $port.endPort) (int $port.port)) 60000) }}+{{- fail (printf "workers.networkPolicy.extraIngress[%d].ports[%d] spans nearly every port (%v-%v): list the worker ports instead." $index $portIndex $port.port $port.endPort) }}+{{- end }}+{{- end }}+{{- end }}+{{- $maxWorkerChildCount := int (include "sie-cluster.worker.maxChildCount" .) }}+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: {{ include "sie-cluster.fullname" . }}-worker+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.worker.labels" . | nindent 4 }}+spec:+ podSelector:+ matchLabels:+ {{- include "sie-cluster.worker.selectorLabels" . | nindent 6 }}+ policyTypes:+ - Ingress+ ingress:+ - from:+ - podSelector:+ matchLabels:+ {{- include "sie-cluster.gateway.selectorLabels" . | nindent 14 }}+ ports:+ {{- range $i := until $maxWorkerChildCount }}+ - port: {{ add $.Values.workers.common.port $i }}+ protocol: TCP+ {{- end }}+ {{- with $networkPolicy.extraIngress }}+ {{- toYaml . | nindent 4 }}+ {{- end }}+{{- end }}diff --git a/deploy/helm/sie-cluster/values-aks.yaml b/deploy/helm/sie-cluster/values-aks.yamlindex d6c317aac..849357da8 100644--- a/deploy/helm/sie-cluster/values-aks.yaml+++ b/deploy/helm/sie-cluster/values-aks.yaml@@ -56,9 +56,10 @@ machineProfiles:machineType: Standard_NV6ads_A10_v5spot: true-# Ingress via nginx-ingress+# Ingress via nginx-ingress. Off by default: install an ingress controller,+# then enable it with hosts, TLS, and gateway auth (see the chart README).ingress:- enabled: true+ enabled: falseclassName: nginx# TLS defaults to BYO (user-supplied kubernetes.io/tls Secret).# Three other modes are supported:diff --git a/deploy/helm/sie-cluster/values-aws.yaml b/deploy/helm/sie-cluster/values-aws.yamlindex 1d62da447..ac7772060 100644--- a/deploy/helm/sie-cluster/values-aws.yaml+++ b/deploy/helm/sie-cluster/values-aws.yaml@@ -48,9 +48,10 @@ machineProfiles:machineType: g6.xlargespot: false-# Ingress via nginx-ingress (matches GCP)+# Ingress via nginx-ingress. Off by default: install an ingress controller,+# then enable it with hosts, TLS, and gateway auth (see the chart README).ingress:- enabled: true+ enabled: falseclassName: nginx# TLS defaults to BYO (user-supplied kubernetes.io/tls Secret).# Three other modes are supported:diff --git a/deploy/helm/sie-cluster/values-gke.yaml b/deploy/helm/sie-cluster/values-gke.yamlindex a0cd68e64..46512c7f1 100644--- a/deploy/helm/sie-cluster/values-gke.yaml+++ b/deploy/helm/sie-cluster/values-gke.yaml@@ -61,9 +61,10 @@ dashboards:healthGates:enabled: true-# Ingress via nginx-ingress (install externally or via ingress-nginx chart)+# Ingress via nginx-ingress. Off by default: install an ingress controller,+# then enable it with hosts, TLS, and gateway auth (see the chart README).ingress:- enabled: true+ enabled: falseclassName: nginx# TLS defaults to BYO (user-supplied kubernetes.io/tls Secret).# Three other modes are supported:diff --git a/deploy/helm/sie-cluster/values-ha.yaml b/deploy/helm/sie-cluster/values-ha.yamlindex 106fc9f2b..4c134454e 100644--- a/deploy/helm/sie-cluster/values-ha.yaml+++ b/deploy/helm/sie-cluster/values-ha.yaml@@ -10,7 +10,10 @@# * a three-member NATS cluster with a JetStream file store on each member;# * work-queue streams created file-backed and replicated across all three,# so a broker restart or a single-member loss keeps queued and in-flight-# work.+# work;+# * a worker NetworkPolicy that admits connections to the worker HTTP ports+# only from this release's gateway pods (needs a NetworkPolicy-enforcing+# CNI; add workers.networkPolicy.extraIngress for other direct callers).## Layer it under a provider overlay:#@@ -45,3 +48,7 @@ nats:queueRouting:streamStorage: filestreamReplicas: 3++workers:+ networkPolicy:+ enabled: truediff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex ef0c751a3..6935ebcfd 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -266,9 +266,20 @@ gateway:# -- Service configurationservice:+ # -- LoadBalancer or NodePort requires gateway auth (auth.mode=static) or+ # allowUnauthenticated=true, because those Services are reachable from+ # outside the cluster on most managed platforms.type: ClusterIPport: 8080annotations: {}+ # -- Allow a LoadBalancer or NodePort gateway Service without gateway auth+ # (a boolean).+ allowUnauthenticated: false+ # -- Acknowledge that a LoadBalancer or NodePort gateway Service serves+ # plain HTTP (a boolean). Required for those types; configure TLS+ # termination through provider annotations above when the load balancer+ # supports it, or prefer an Ingress with TLS.+ allowPlaintext: false# -- Block the gateway pod on sie-config readiness before it starts the# cold-start bootstrap. Prevents the rolling-upgrade race where the@@ -841,6 +852,23 @@ workers:cpu: "2"memory: "2Gi"+ # -- Ingress NetworkPolicy for worker pods. When enabled, this policy admits+ # only this release's gateway pods to the worker HTTP ports (the worker API+ # has no authentication of its own); kubelet probes and in-pod sidecar+ # traffic are unaffected. Requires a CNI that enforces NetworkPolicy.+ # 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.+ networkPolicy:+ enabled: false+ # -- Additional NetworkPolicy ingress rules for callers outside this chart+ # that must reach workers directly. Each entry needs a non-empty `from`+ # (scoped selectors, or an ipBlock with a prefix length above /0) and+ # `ports` (each with a port, and no range wider than 60000 ports). These+ # checks catch mistakes, not every broad rule. Disable the policy instead+ # to open the worker API to everything.+ extraIngress: []+# -- Worker pools (one StatefulSet per enabled queuePool/machineProfile/bundle lane)# Each map entry creates a WorkerGroup family: one StatefulSet + one# pre-pull DaemonSet per enabled bundle.@@ -1145,6 +1173,18 @@ ingress:enabled: falseclassName: nginxannotations: {}+ # -- Allow the gateway Ingress while nothing authenticates requests (gateway+ # auth mode none and auth.enabled=false). The chart refuses that render by+ # default, whatever the hosts and TLS, because it publishes the inference API+ # and the pool API, which keeps GPU workers warm, to anyone who can reach the+ # ingress controller. Set true (a boolean) only when the controller is+ # private or another layer in front of it authenticates every request.+ allowUnauthenticated: false+ # -- Allow the gateway Ingress without TLS. The chart refuses an Ingress that+ # carries no TLS (tlsConfig.enabled with at least one host) unless+ # tlsConfig.mode=disabled states that TLS terminates upstream. Set true (a+ # boolean) to serve plain HTTP, which sends tokens and cookies in cleartext.+ allowPlaintext: false# -- Hostnames served by the ingress. Each entry becomes an ingress rule and,# when tls.enabled, a SAN on the TLS cert (all hosts share tls.secretName).# Empty => host-less catch-all ingress.@@ -1264,6 +1304,13 @@ auth:ingress:authResponseHeaders:- Authorization+ # -- IngressClass spec.controller values whose controller honours the+ # nginx.ingress.kubernetes.io/auth-* annotations the edge relies on. Add a+ # second ingress-nginx controller's own controller string (for example+ # k8s.io/internal-ingress-nginx) here. The NGINX Inc controller+ # (nginx.org/ingress-controller) ignores these annotations; never list it.+ acceptedControllers:+ - k8s.io/ingress-nginx# -- Service account configuration# NAMING CONTRACT: The KSA name below ("sie-server") MUST match the name used in@@ -2176,6 +2223,11 @@ mcpEdge:# gateway ingress (/ -> gateway). Reuses the chart's nginx + cert-manager.enabled: falsehost: ""+ # -- Serve the MCP edge Ingress without TLS (a boolean). The chart refuses+ # it by default because it carries connector secrets and OAuth tokens;+ # ingress.tlsConfig.enabled, or mode=disabled when TLS terminates+ # upstream, satisfies the check.+ allowPlaintext: falseresources:requests:cpu: "100m"diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex b8ea8c2eb..150e2c753 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -106,6 +106,9 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` | `false` | Act on the per-lane decision. Off = shadow mode: the decision is computed and recorded, and admission is governed by `SIE_GATEWAY_MAX_STREAM_PENDING` alone. On = a saturated lane gets a targeted 503 while other lanes on the same pool keep admitting || `SIE_GATEWAY_DEFAULT_MAX_TOKENS` | `1024` | Output-token cap applied to `/v1/chat/completions` requests that omit both `max_completion_tokens` and `max_tokens`. OpenAI treats the field as optional, so the gateway defaults rather than rejecting — generic clients (Open WebUI) rely on this || `SIE_GATEWAY_ENABLE_POOLS` | `false` | Enable pool management |+| `SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT` | `4` | Largest number of workers one API-created pool may keep warm. `POST /v1/pools` rejects with `400 INVALID_REQUEST` a `minimum_worker_count` whose total across the pool's machine profiles (the floor applies to each profile) exceeds it, and `gpus` requirements summing to more than it. A pool stored before this budget existed is allotted it in machine-profile name order: it becomes Active once the allotted workers are available, its active lease keeps only those warm, and its warm floor is spread over its lanes (at least one worker each on as many lanes as the budget allows). Static Helm queue pools are exempt |+| `SIE_GATEWAY_POOL_MAX_TTL_S` | `3600` | Largest `ttl_seconds` `POST /v1/pools` accepts; larger values get `400 INVALID_REQUEST`. The lease of any stored pool, including one restored from Kubernetes, expires no later than this many seconds after its last renewal. `0` is ignored with a warning |+| `SIE_GATEWAY_MAX_POOLS` | `64` | Largest number of live API-created pools (the `default` pool and static Helm queue pools do not count). Creating one more gets `403 POOL_OPERATION_FORBIDDEN`; `0` disables API pool creation. Each replica checks the pools it knows, including ones replicated from other gateways, so concurrent creates on different replicas can briefly exceed it || `SIE_GATEWAY_HOT_RELOAD` | `false` | Enable filesystem watcher for bundle/model directories || `SIE_GATEWAY_WATCH_POLLING` | `false` | Use polling file-watcher instead of inotify/fsevents (alias: `SIE_GATEWAY_POLLING_WATCHER`). Useful on filesystems where native notifications are unreliable || `SIE_CONFIG_SERVICE_URL` | unset | Base URL of `sie-config`. When set, the gateway runs a background `GET /v1/configs/export` bootstrap on startup and a 30 s `GET /v1/configs/epoch` drift poller, and `/readyz` returns `503` until the first complete export is applied. When unset, the bootstrap/poller tasks no-op and the gateway runs filesystem-seed-only |diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex f965be314..4b7cf5645 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -918,6 +918,6 @@ A pool spec may also carry `minimum_worker_count` (a per-pool warm floor, defaulA pool spec may also carry `pinned_models` (a per-pool set of always-loaded models, default empty), chosen from the models the gateway already tracks (`GET /v1/configs/models`); ids may be profile-qualified (`model-name:profile_name`, the registry's `{base}:{profile}` variant entries, with `model:default` folding to the base). The API validates each id against the registry and stores it canonicalized. Every 30 seconds the gateway emits the complete `sie.gateway.pool.pinned_model.loaded{pool,model}` snapshot through its canonical OTel facade: the value is `1` only when a healthy worker assigned to that logical pool reports the model loaded, and removed pools or pins are explicitly zeroed. Actually keeping the models loaded (worker preload) and lazy-load/LRU using spare capacity around the pinned set are worker-side and tracked separately. Default empty leaves lazy-loading unchanged.-Creating a usable custom pool has two supported shapes. For a dynamic logical pool over base capacity, call `POST /v1/pools` with the logical name and GPU requirements and omit `queue_pool`; it defaults to `default`, so no additional Helm worker group is required. Pool `name` is user/dynamic. Non-default `queue_pool` is infra/admin: it must name a Helm-rendered `queuePool`/`SIE_POOL` backing lane declared under `queueRouting.staticQueuePools`. For a dedicated physical queue, first add that worker group to Helm values and declare the same name under `queueRouting.staticQueuePools`, then create logical pools with `queue_pool` set to that queue. Lease-owned dynamic pools expire after their TTL unless renewed with `POST /v1/pools/{name}/renew`. Clients target either shape with an explicit `X-SIE-POOL` header, for example `X-SIE-POOL: customer-acme`, or SDK `gpu="customer-acme/l4"`. The `default` pool is protected and cannot be deleted. Missing named pools intentionally fail closed so capped/dynamic pool isolation is not weakened by a silent fallback.+Creating a usable custom pool has two supported shapes. For a dynamic logical pool over base capacity, call `POST /v1/pools` with the logical name and GPU requirements and omit `queue_pool`; it defaults to `default`, so no additional Helm worker group is required. Pool `name` is user/dynamic. Non-default `queue_pool` is infra/admin: it must name a Helm-rendered `queuePool`/`SIE_POOL` backing lane declared under `queueRouting.staticQueuePools`. For a dedicated physical queue, first add that worker group to Helm values and declare the same name under `queueRouting.staticQueuePools`, then create logical pools with `queue_pool` set to that queue. Lease-owned dynamic pools expire after their TTL unless renewed with `POST /v1/pools/{name}/renew`. The gateway bounds API-created pools independently of auth: a `minimum_worker_count` whose total across the pool's machine profiles, or `gpus` requirements whose sum, exceeds `SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT` (default 4) and `ttl_seconds` above `SIE_GATEWAY_POOL_MAX_TTL_S` (default 3600) are rejected with `400 INVALID_REQUEST`, and a create beyond `SIE_GATEWAY_MAX_POOLS` live API-created pools (default 64) is rejected with `403 POOL_OPERATION_FORBIDDEN`. Pools restored from Kubernetes or applied from another replica are held to the same TTL and warm-floor caps when their lease expiry and KEDA warm floor are computed. An API-created pool's active lease keeps at most its `gpus` requirement per machine profile warm, and at most `SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT` in total, however many workers it is assigned; a stored pool's per-lane warm floor is capped so its total fits the same budget. The live-pool cap is checked by the replica serving the create against every pool it knows, so concurrent creates on different replicas can briefly exceed it. `POST /v1/pools` refuses the name `default` with `403 POOL_OPERATION_FORBIDDEN`. The `default` pool and static Helm queue pools are operator-owned and exempt. Clients target either shape with an explicit `X-SIE-POOL` header, for example `X-SIE-POOL: customer-acme`, or SDK `gpu="customer-acme/l4"`. The `default` pool is protected and cannot be deleted. Missing named pools intentionally fail closed so capped/dynamic pool isolation is not weakened by a silent fallback.Model configs registered via the control plane (`sie-config`) may carry a top-level `pool` field. That field is model routing/config assignment: omitted or empty means `default`, and a request that omits `X-SIE-POOL` defaults to the model's assigned pool. It does not create workers, KEDA ScaledObjects, or runtime pool leases. Worker counts, machine profiles, bundles, and autoscaling lanes are still Helm-driven physical capacity; `/v1/pools` and `queueRouting.staticQueuePools` only create or renew runtime admission/capacity state, optionally backed by existing `default` capacity through `PoolSpec.queue_pool`. In the Kubernetes/Helm composition, workers filter materialized model configs by their physical `SIE_POOL`, so a model config for a dedicated queue normally uses the physical queue-pool name; gateway requests may still target a logical pool whose `queue_pool` resolves to that physical name. A default-backed logical pool should not use a non-default model-config `pool` unless a matching dedicated worker queue exists. The managed Modal composition has one governed exception: a deployment-owned diagnostic admission queue may reuse the complete `default` catalog in a separate worker app. Dispatch stays on that physical queue, but bundle-hash and immutable-revision evidence are atomically scoped to the requested model's declared catalog pool. A known catalog model with a missing scoped hash fails closed rather than enabling the empty-hash wildcard; unknown sealed compatibility remains separately bounded.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 148111e18..0f4adc955 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -1037,13 +1037,14 @@"minimum": 0,"type": "integer"},+ "description": "Required workers per machine profile. Requirements summing to more\nthan the gateway limit (`SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT`,\ndefault 4) are rejected.","propertyNames": {"type": "string"},"type": "object"},"minimum_worker_count": {- "description": "Per-pool warm floor (minimum machines kept warm via KEDA). Default 0\nkeeps scale-from-zero. See `PoolSpec::minimum_worker_count`.",+ "description": "Per-pool warm floor (minimum machines kept warm via KEDA). Default 0\nkeeps scale-from-zero. It applies to each of the pool's machine\nprofiles; a floor whose total across profiles exceeds the gateway limit\n(`SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT`, default 4) is rejected.\nSee `PoolSpec::minimum_worker_count`.","format": "int32","minimum": 0,"type": "integer"@@ -1073,6 +1074,7 @@]},"ttl_seconds": {+ "description": "Lease TTL in seconds; omit for the gateway default. Values above the\ngateway limit (`SIE_GATEWAY_POOL_MAX_TTL_S`, default 3600) are rejected.","format": "int64","minimum": 0,"type": [@@ -6823,7 +6825,7 @@}}},- "description": "Invalid pool request"+ "description": "Invalid pool request, including a TTL or warm floor above the gateway limit"},"401": {"content": {@@ -6843,7 +6845,7 @@}}},- "description": "Valid bearer token but admin token required for this mutation (or admin token not configured)"+ "description": "Admin token required for this mutation (or admin token not configured), the pool is named `default`, or the gateway's limit on API-created pools is reached"},"500": {"content": {diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex e5aeef152..568d3b8ed 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -5,6 +5,7 @@ use std::time::Duration;use serde::Deserialize;use crate::state::demand_tracker::PhysicalLaneCatalog;+use crate::state::pool_manager::PoolLimits;use crate::types::pool::PoolSpec;/// Modal platform proxy-auth credential.@@ -480,6 +481,55 @@ fn env_u64(key: &str, fallback: u64) -> u64 {.unwrap_or(fallback)}+/// Read the pool API bounds from `SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT`,+/// `SIE_GATEWAY_POOL_MAX_TTL_S`, and `SIE_GATEWAY_MAX_POOLS`. An unset value+/// keeps that bound's default; an unparsable one keeps it with a warning.+pub fn pool_limits_from_env() -> PoolLimits {+ let defaults = PoolLimits::default();+ PoolLimits {+ max_minimum_worker_count: env_pool_limit(+ "SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT",+ defaults.max_minimum_worker_count,+ ),+ max_ttl_seconds: match env_pool_limit(+ "SIE_GATEWAY_POOL_MAX_TTL_S",+ defaults.max_ttl_seconds,+ ) {+ 0 => {+ tracing::warn!(+ env = "SIE_GATEWAY_POOL_MAX_TTL_S",+ default = defaults.max_ttl_seconds,+ "ignoring a zero pool TTL limit, which would expire every pool at once; using the default"+ );+ defaults.max_ttl_seconds+ }+ ttl => ttl,+ },+ max_pools: env_pool_limit("SIE_GATEWAY_MAX_POOLS", defaults.max_pools),+ }+}++fn env_pool_limit<T>(key: &str, default: T) -> T+where+ T: std::str::FromStr + std::fmt::Display + Copy,+{+ let Ok(raw) = env::var(key) else {+ return default;+ };+ match raw.trim().parse() {+ Ok(value) => value,+ Err(_) => {+ tracing::warn!(+ env = key,+ value = %raw,+ default = %default,+ "ignoring unparsable pool limit; using the default"+ );+ default+ }+ }+}+fn env_csv(key: &str) -> Vec<String> {match env::var(key) {Ok(s) if !s.is_empty() => s@@ -1102,6 +1152,53 @@ mod tests {});}+ #[test]+ fn test_pool_limits_from_env_defaults_and_overrides() {+ let keys = [+ "SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT",+ "SIE_GATEWAY_POOL_MAX_TTL_S",+ "SIE_GATEWAY_MAX_POOLS",+ ];+ without_env(&keys, || {+ assert_eq!(pool_limits_from_env(), PoolLimits::default());+ });+ with_env(+ &[+ ("SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT", "0"),+ ("SIE_GATEWAY_POOL_MAX_TTL_S", " 86400 "),+ ("SIE_GATEWAY_MAX_POOLS", "not-a-number"),+ ],+ || {+ assert_eq!(+ pool_limits_from_env(),+ PoolLimits {+ max_minimum_worker_count: 0,+ max_ttl_seconds: 86_400,+ max_pools: PoolLimits::default().max_pools,+ }+ );+ },+ );+ }++ #[test]+ fn test_pool_limits_ignore_a_zero_ttl_limit_but_keep_zero_pools() {+ with_env(+ &[+ ("SIE_GATEWAY_POOL_MAX_TTL_S", "0"),+ ("SIE_GATEWAY_MAX_POOLS", "0"),+ ],+ || {+ let limits = pool_limits_from_env();+ assert_eq!(+ limits.max_ttl_seconds,+ PoolLimits::default().max_ttl_seconds+ );+ assert_eq!(limits.max_pools, 0);+ },+ );+ }+#[test]fn test_env_json_string_map() {with_env(&[("_TEST_JSON_MAP", r#"{"l4":"l4-spot"}"#)], || {diff --git a/packages/sie_gateway/src/handlers/pools.rs b/packages/sie_gateway/src/handlers/pools.rsindex 1abd24e37..39a256975 100644--- a/packages/sie_gateway/src/handlers/pools.rs+++ b/packages/sie_gateway/src/handlers/pools.rs@@ -12,7 +12,7 @@ use utoipa::ToSchema;use crate::http_error::{code as err_code, json_detail};use crate::server::AppState;use crate::state::model_registry::ModelRegistry;-use crate::state::pool_manager::DEFAULT_POOL_NAME;+use crate::state::pool_manager::{PoolLimitError, DEFAULT_POOL_NAME};#[derive(Debug, Deserialize, ToSchema)]pub struct CreatePoolRequest {@@ -23,16 +23,24 @@ pub struct CreatePoolRequest {/// `queueRouting.staticQueuePools` for dedicated capacity.#[serde(default)]pub queue_pool: Option<String>,+ /// Required workers per machine profile. Requirements summing to more+ /// than the gateway limit (`SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT`,+ /// default 4) are rejected.#[serde(default)]pub gpus: HashMap<String, u32>,#[serde(default)]pub gpu_caps: HashMap<String, u32>,#[serde(default)]pub bundle: Option<String>,+ /// Lease TTL in seconds; omit for the gateway default. Values above the+ /// gateway limit (`SIE_GATEWAY_POOL_MAX_TTL_S`, default 3600) are rejected.#[serde(default)]pub ttl_seconds: Option<u64>,/// Per-pool warm floor (minimum machines kept warm via KEDA). Default 0- /// keeps scale-from-zero. See `PoolSpec::minimum_worker_count`.+ /// keeps scale-from-zero. It applies to each of the pool's machine+ /// profiles; a floor whose total across profiles exceeds the gateway limit+ /// (`SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT`, default 4) is rejected.+ /// See `PoolSpec::minimum_worker_count`.#[serde(default)]pub minimum_worker_count: u32,/// Per-pool pinned-model set. Each id is validated against the models the@@ -96,7 +104,8 @@ fn canonicalize_pinned_models(request_body = CreatePoolRequest,responses((status = 201, description = "Pool created, renewed, or updated", body = crate::types::pool::Pool),- (status = 400, description = "Invalid pool request", body = crate::openapi::StandardApiError)+ (status = 400, description = "Invalid pool request, including a TTL or warm floor above the gateway limit", body = crate::openapi::StandardApiError),+ (status = 403, description = "Admin token required for this mutation (or admin token not configured), the pool is named `default`, or the gateway's limit on API-created pools is reached", body = crate::openapi::StandardApiError)))]pub async fn create_pool(@@ -114,6 +123,17 @@ pub async fn create_pool(.into_response();}+ if req.name.eq_ignore_ascii_case(DEFAULT_POOL_NAME) {+ return (+ StatusCode::FORBIDDEN,+ Json(json_detail(+ err_code::POOL_OPERATION_FORBIDDEN,+ "The default pool is managed by the gateway and cannot be created or modified through the API",+ )),+ )+ .into_response();+ }+if req.gpus.is_empty() && req.gpu_caps.is_empty() {return (StatusCode::BAD_REQUEST,@@ -158,14 +178,22 @@ pub async fn create_pool(info!(event = "pool.create", pool = %req.name, status = 201u16, "audit");(StatusCode::CREATED, Json(json!(pool))).into_response()}- Err(e) => (- StatusCode::BAD_REQUEST,- Json(json_detail(err_code::INVALID_REQUEST, e.to_string())),- )- .into_response(),+ Err(e) => create_pool_error_response(e.as_ref()),}}+fn create_pool_error_response(+ error: &(dyn std::error::Error + Send + Sync + 'static),+) -> axum::response::Response {+ let (status, code) = match error.downcast_ref::<PoolLimitError>() {+ Some(PoolLimitError::TooManyPools { .. }) => {+ (StatusCode::FORBIDDEN, err_code::POOL_OPERATION_FORBIDDEN)+ }+ _ => (StatusCode::BAD_REQUEST, err_code::INVALID_REQUEST),+ };+ (status, Json(json_detail(code, error.to_string()))).into_response()+}+#[utoipa::path(get,path = "/v1/pools",@@ -414,6 +442,54 @@ mod tests {assert_eq!(out, vec!["test/model".to_string()]);}+ async fn error_body(response: axum::response::Response) -> serde_json::Value {+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ serde_json::from_slice(&bytes).unwrap()+ }++ #[tokio::test]+ async fn pool_limit_is_a_forbidden_pool_operation() {+ let response = create_pool_error_response(&PoolLimitError::TooManyPools { max: 64 });+ assert_eq!(response.status(), StatusCode::FORBIDDEN);+ let body = error_body(response).await;+ assert_eq!(body["detail"]["code"], err_code::POOL_OPERATION_FORBIDDEN);+ assert!(body["detail"]["message"]+ .as_str()+ .unwrap()+ .contains("SIE_GATEWAY_MAX_POOLS"));+ }++ #[tokio::test]+ async fn spec_limits_are_invalid_requests() {+ for error in [+ PoolLimitError::MinimumWorkerCount {+ requested: 10,+ max: 4,+ },+ PoolLimitError::WarmFloorTotal {+ minimum_worker_count: 4,+ profiles: 3,+ max: 4,+ },+ PoolLimitError::GpuRequirementTotal {+ requested: 6,+ max: 4,+ },+ PoolLimitError::Ttl {+ requested: u64::MAX,+ max: 3600,+ },+ ] {+ let response = create_pool_error_response(&error);+ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ let body = error_body(response).await;+ assert_eq!(body["detail"]["code"], err_code::INVALID_REQUEST);+ assert_eq!(body["detail"]["message"], error.to_string());+ }+ }+#[test]fn canonicalize_empty_is_ok_empty() {let (registry, _bundles, _models) = seeded_registry();diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex d85cea912..ad889d6b3 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -209,7 +209,8 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {let pools_enabled = config.enable_pools || config.use_kubernetes;// Set up pool manager (created early so on_worker_healthy callback can capture it)- let mut pm = PoolManager::new(config.configured_gpus.clone());+ let mut pm = PoolManager::new(config.configured_gpus.clone())+ .with_limits(config::pool_limits_from_env());let mut k8s_pool_backend: Option<Arc<state::k8s_pool_backend::K8sPoolBackend>> = None;if config.use_kubernetes && pools_enabled {match state::k8s_pool_backend::K8sPoolBackend::new(&config.k8s_namespace, &router_id).awaitdiff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex fd0109785..504a4da4b 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -1062,6 +1062,55 @@ mod flat_404_tests {);}+ async fn post_pool(app: &Router, body: serde_json::Value) -> (StatusCode, serde_json::Value) {+ let response = app+ .clone()+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/v1/pools")+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap(),+ )+ .await+ .unwrap();+ let status = response.status();+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();+ (status, serde_json::from_slice(&bytes).unwrap())+ }++ #[tokio::test]+ async fn test_create_pool_refuses_the_default_pool_name() {+ let (app, _bundles_dir, _models_dir) = build_router();+ for name in ["default", "DEFAULT"] {+ let (status, body) =+ post_pool(&app, serde_json::json!({"name": name, "gpus": {"l4": 0}})).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "{name}");+ assert_eq!(body["detail"]["code"], "POOL_OPERATION_FORBIDDEN");+ }+ }++ #[tokio::test]+ async fn test_create_pool_rejects_limits_through_the_router() {+ let (app, _bundles_dir, _models_dir) = build_router();+ for body in [+ serde_json::json!({"name": "bench", "gpus": {"l4": 1}, "minimum_worker_count": 99}),+ serde_json::json!({"name": "bench", "gpus": {"l4": 1}, "ttl_seconds": 86_400}),+ serde_json::json!({"name": "bench", "gpus": {"l4": 6}}),+ ] {+ let (status, detail) = post_pool(&app, body).await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert_eq!(detail["detail"]["code"], "INVALID_REQUEST");+ }+ let (status, _) = post_pool(+ &app,+ serde_json::json!({"name": "bench", "gpus": {"l4": 1}}),+ )+ .await;+ assert_eq!(status, StatusCode::CREATED);+ }+#[tokio::test]async fn test_files_routes_return_flat_404() {let (app, _bundles_dir, _models_dir) = build_router();diff --git a/packages/sie_gateway/src/state/pool_manager.rs b/packages/sie_gateway/src/state/pool_manager.rsindex 77f23aa46..388ddb616 100644--- a/packages/sie_gateway/src/state/pool_manager.rs+++ b/packages/sie_gateway/src/state/pool_manager.rs@@ -11,8 +11,98 @@ use crate::types::pool::{AssignedWorker, Pool, PoolSpec, PoolState, PoolStatus};pub const DEFAULT_POOL_NAME: &str = "default";const DEFAULT_LEASE_DURATION_S: f64 = 1200.0; // 20 minutesconst TIMESTAMP_TOLERANCE_S: f64 = 0.001;+pub const DEFAULT_POOL_MAX_MINIMUM_WORKER_COUNT: u32 = 4;+pub const DEFAULT_POOL_MAX_TTL_SECONDS: u64 = 3600;+pub const DEFAULT_MAX_POOLS: usize = 64;type WorkerAssignment = (String, String, String, String, String);+/// Bounds on pools created through the pool API. The `default` pool and+/// static Helm queue pools are operator-owned and never bounded here.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct PoolLimits {+ /// Largest number of workers an API pool may keep warm: bounds the warm+ /// floor summed over the pool's machine profiles (`minimum_worker_count`+ /// applies to each profile) and the `gpus` requirement summed over+ /// profiles, and caps what a stored pool exports through its warm floor+ /// and active lease.+ pub max_minimum_worker_count: u32,+ /// Largest accepted `ttl_seconds`; also caps the effective lease of any+ /// stored pool, including pools restored from Kubernetes.+ pub max_ttl_seconds: u64,+ /// Largest number of live API-created pools, checked by the replica that+ /// serves the create against every pool it knows, including pools applied+ /// from other replicas. Concurrent creates on different replicas can pass+ /// the check before either sees the other's pool.+ pub max_pools: usize,+}++impl Default for PoolLimits {+ fn default() -> Self {+ Self {+ max_minimum_worker_count: DEFAULT_POOL_MAX_MINIMUM_WORKER_COUNT,+ max_ttl_seconds: DEFAULT_POOL_MAX_TTL_SECONDS,+ max_pools: DEFAULT_MAX_POOLS,+ }+ }+}++#[derive(Debug, PartialEq, Eq)]+pub enum PoolLimitError {+ MinimumWorkerCount {+ requested: u32,+ max: u32,+ },+ WarmFloorTotal {+ minimum_worker_count: u32,+ profiles: usize,+ max: u32,+ },+ GpuRequirementTotal {+ requested: u64,+ max: u32,+ },+ Ttl {+ requested: u64,+ max: u64,+ },+ TooManyPools {+ max: usize,+ },+}++impl std::fmt::Display for PoolLimitError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ PoolLimitError::MinimumWorkerCount { requested, max } => write!(+ f,+ "minimum_worker_count {requested} exceeds the gateway limit of {max} (SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT)"+ ),+ PoolLimitError::WarmFloorTotal {+ minimum_worker_count,+ profiles,+ max,+ } => write!(+ f,+ "minimum_worker_count {minimum_worker_count} applies to each of the pool's {profiles} machine profiles, which exceeds the gateway limit of {max} warm workers per pool (SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT)"+ ),+ PoolLimitError::GpuRequirementTotal { requested, max } => write!(+ f,+ "gpus requirements total {requested} across machine profiles, which exceeds the gateway limit of {max} per pool (SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT)"+ ),+ PoolLimitError::Ttl { requested, max } => write!(+ f,+ "ttl_seconds {requested} exceeds the gateway limit of {max} (SIE_GATEWAY_POOL_MAX_TTL_S)"+ ),+ PoolLimitError::TooManyPools { max } => write!(+ f,+ "Pool limit reached: the gateway already holds {max} API-created pools (SIE_GATEWAY_MAX_POOLS); delete a pool or let one expire first"+ ),+ }+ }+}++impl std::error::Error for PoolLimitError {}+#[derive(Debug)]pub enum PoolDeletionProtectedError {Default,@@ -157,6 +247,7 @@ pub struct PoolManager {static_pool_names: RwLock<HashSet<String>>,/// Optional K8s ConfigMap backend for pool persistence.k8s_backend: Option<Arc<K8sPoolBackend>>,+ limits: PoolLimits,}impl PoolManager {@@ -167,9 +258,15 @@ impl PoolManager {configured_profiles,static_pool_names: RwLock::new(HashSet::new()),k8s_backend: None,+ limits: PoolLimits::default(),}}+ pub fn with_limits(mut self, limits: PoolLimits) -> Self {+ self.limits = limits;+ self+ }+/// Attach a K8s pool backend for persistent pool storage.#[allow(dead_code)]pub fn with_k8s_backend(mut self, backend: Arc<K8sPoolBackend>) -> Self {@@ -233,12 +330,17 @@ impl PoolManager {.as_secs_f64()}- /// Compute the Lease TTL in whole seconds from the pool spec or global default.- fn lease_ttl_seconds(pool: &Pool) -> i32 {+ /// Lease TTL in whole seconds: the pool's own TTL or the gateway default,+ /// capped at `PoolLimits::max_ttl_seconds`.+ fn effective_ttl_seconds(&self, pool: &Pool) -> u64 {pool.spec.ttl_seconds- .map(|s| s.min(i32::MAX as u64) as i32)- .unwrap_or((DEFAULT_LEASE_DURATION_S as u64).min(i32::MAX as u64) as i32)+ .unwrap_or(self.lease_duration_s as u64)+ .min(self.limits.max_ttl_seconds)+ }++ fn lease_ttl_seconds(&self, pool: &Pool) -> i32 {+ self.effective_ttl_seconds(pool).min(i32::MAX as u64) as i32}fn normalize_gpus_and_caps(@@ -287,6 +389,114 @@ impl PoolManager {}}+ /// Per-profile requirements an API pool is held to: its own requirements,+ /// allotted in profile-name order until `max_minimum_worker_count` runs+ /// out. Equal to the requirements for every pool the API accepts; smaller+ /// only for a pool stored before the budget existed.+ fn capped_requirements(&self, pool: &Pool) -> HashMap<String, u32> {+ let mut merged: HashMap<String, u32> = HashMap::new();+ for (profile, required) in &pool.spec.gpus {+ let entry = merged.entry(profile.to_ascii_lowercase()).or_insert(0);+ *entry = entry.saturating_add(*required);+ }+ let mut requirements: Vec<(String, u32)> = merged.into_iter().collect();+ requirements.sort();+ let mut left = self.limits.max_minimum_worker_count;+ let mut capped = HashMap::new();+ for (profile, required) in requirements {+ let allotted = required.min(left);+ left -= allotted;+ capped.insert(profile, allotted);+ }+ capped+ }++ /// Assigned workers an API pool keeps warm through its active lease: per+ /// machine profile, at most its capped requirement, so at most+ /// `max_minimum_worker_count` in total.+ fn leased_workers(&self, pool: &Pool) -> Vec<AssignedWorker> {+ let mut remaining = self.capped_requirements(pool);+ pool.status+ .assigned_workers+ .iter()+ .filter(+ |worker| match remaining.get_mut(&worker.gpu.to_ascii_lowercase()) {+ Some(left) if *left > 0 => {+ *left -= 1;+ true+ }+ _ => false,+ },+ )+ .cloned()+ .collect()+ }++ /// Fit a stored API pool's warm floor, which applies to each of its lanes,+ /// into `max_minimum_worker_count`: spread the budget evenly over the+ /// lanes, and when there are more lanes than budget, keep one warm worker+ /// on each of the first lanes in name order.+ fn fit_warm_floor_to_budget(&self, snapshot: &mut CapacityPoolSnapshot) {+ let budget = self.limits.max_minimum_worker_count;+ let floor = snapshot.minimum_worker_count.min(budget);+ let lanes = snapshot.machine_profiles.len() as u64;+ snapshot.minimum_worker_count = floor;+ if floor == 0 || u64::from(floor) * lanes <= u64::from(budget) {+ return;+ }+ let per_lane = u32::try_from(u64::from(budget) / lanes).unwrap_or(0);+ if per_lane > 0 {+ snapshot.minimum_worker_count = per_lane;+ } else {+ snapshot.machine_profiles.sort();+ snapshot.machine_profiles.truncate(budget as usize);+ snapshot.minimum_worker_count = 1;+ }+ }++ fn check_pool_spec_limits(+ &self,+ gpus: &HashMap<String, u32>,+ ttl_seconds: Option<u64>,+ minimum_worker_count: u32,+ ) -> Result<(), PoolLimitError> {+ let max = self.limits.max_minimum_worker_count;+ if minimum_worker_count > max {+ return Err(PoolLimitError::MinimumWorkerCount {+ requested: minimum_worker_count,+ max,+ });+ }+ let profiles = gpus+ .keys()+ .map(|profile| profile.to_ascii_lowercase())+ .collect::<HashSet<_>>()+ .len();+ if u64::from(minimum_worker_count) * profiles as u64 > u64::from(max) {+ return Err(PoolLimitError::WarmFloorTotal {+ minimum_worker_count,+ profiles,+ max,+ });+ }+ let required: u64 = gpus.values().map(|count| u64::from(*count)).sum();+ if required > u64::from(max) {+ return Err(PoolLimitError::GpuRequirementTotal {+ requested: required,+ max,+ });+ }+ if let Some(ttl) = ttl_seconds {+ if ttl > self.limits.max_ttl_seconds {+ return Err(PoolLimitError::Ttl {+ requested: ttl,+ max: self.limits.max_ttl_seconds,+ });+ }+ }+ Ok(())+ }+async fn is_static_pool(&self, name: &str) -> bool {self.static_pool_names.read()@@ -526,6 +736,11 @@ impl PoolManager {queue_pool: queue_pool.clone(),}));}+ let is_default_pool = name == DEFAULT_POOL_NAME;+ if !is_default_pool {+ self.check_pool_spec_limits(&gpus, ttl_seconds, minimum_worker_count)?;+ }+ let static_pool_names = self.static_pool_names.read().await.clone();let now = Self::now_secs();let mut pools = self.pools.write().await;@@ -572,7 +787,7 @@ impl PoolManager {warn!(error = %e, pool = %pool_key, "failed to persist pool update to K8s");}}- let ttl = Self::lease_ttl_seconds(&result);+ let ttl = self.lease_ttl_seconds(&result);if let Err(e) = backend.create_or_renew_lease(&pool_key, ttl).await {warn!(error = %e, pool = %pool_key, "failed to renew K8s Lease");}@@ -582,6 +797,18 @@ impl PoolManager {return Ok(result);}+ if !is_default_pool {+ let api_pools = pools+ .keys()+ .filter(|key| is_api_pool(key, &static_pool_names))+ .count();+ if api_pools >= self.limits.max_pools {+ return Err(Box::new(PoolLimitError::TooManyPools {+ max: self.limits.max_pools,+ }));+ }+ }+let pool = Pool {spec: PoolSpec {name: name.clone(),@@ -612,7 +839,7 @@ impl PoolManager {if let Err(e) = backend.save_pool(&pool).await {warn!(error = %e, pool = %name, "failed to persist pool to K8s");}- let ttl = Self::lease_ttl_seconds(&pool);+ let ttl = self.lease_ttl_seconds(&pool);if let Err(e) = backend.create_or_renew_lease(&name, ttl).await {warn!(error = %e, pool = %name, "failed to create K8s Lease");}@@ -756,10 +983,18 @@ impl PoolManager {/// Clone only the fields required by the KEDA capacity reconciler.pub async fn capacity_pools(&self) -> Vec<CapacityPoolSnapshot> {+ let static_pool_names = self.static_pool_names.read().await.clone();let pools = self.pools.read().await;pools- .values()- .map(CapacityPoolSnapshot::from_pool)+ .iter()+ .map(|(key, pool)| {+ let mut snapshot = CapacityPoolSnapshot::from_pool(pool);+ if is_api_pool(key, &static_pool_names) {+ self.fit_warm_floor_to_budget(&mut snapshot);+ snapshot.assigned_workers = self.leased_workers(pool);+ }+ snapshot+ }).collect()}@@ -835,6 +1070,9 @@ impl PoolManager {.get_mut(&pool_key).expect("pool key resolved from the same map");let queue_pool = normalize_queue_pool(&pool.spec.queue_pool);+ let capped_requirements = (!is_static_pool+ && !pool_key.eq_ignore_ascii_case(DEFAULT_POOL_NAME))+ .then(|| self.capped_requirements(pool));let filtered: Vec<&WorkerAssignment> = available_workers.iter()@@ -871,11 +1109,18 @@ impl PoolManager {.map(|(gpu, cap)| (gpu.to_lowercase(), *cap)).collect();+ let mut seen_profiles: HashSet<String> = HashSet::new();for (gpu_type, required_count) in &pool.spec.gpus {let gpu_lower = gpu_type.to_lowercase();+ if capped_requirements.is_some() && !seen_profiles.insert(gpu_lower.clone()) {+ continue;+ }let available = workers_by_gpu.get_mut(&gpu_lower);let available_count = available.as_ref().map(|workers| workers.len()).unwrap_or(0);- let required = *required_count as usize;+ let required = capped_requirements+ .as_ref()+ .and_then(|capped| capped.get(&gpu_lower).copied())+ .unwrap_or(*required_count) as usize;if available_count < required {all_met = false;@@ -1041,11 +1286,7 @@ impl PoolManager {{continue;}- let ttl = pool- .spec- .ttl_seconds- .map(|s| s as f64)- .unwrap_or(self.lease_duration_s);+ let ttl = self.effective_ttl_seconds(pool) as f64;if now - pool.status.last_renewed > ttl {expired.push(name.clone());}@@ -1136,6 +1377,11 @@ fn known_queue_pool_from_names(static_pool_names: &HashSet<String>, name: &str)queue_pool == DEFAULT_POOL_NAME || static_pool_names.contains(&queue_pool)}+fn is_api_pool(key: &str, static_pool_names: &HashSet<String>) -> bool {+ let name = normalize_pool_name(key);+ name != DEFAULT_POOL_NAME && !static_pool_names.contains(&name)+}+/// Deduplicated, lowercased machine-profile set for a pool, taken from the/// union of `spec.gpus` (requirements) and `spec.gpu_caps` (admission caps)./// This is the same set `demand_profiles_for_pool` fans pending demand across;@@ -2612,4 +2858,555 @@ mod tests {// Should not panic or errorpm.remove_remote_pool("nonexistent").await;}++ fn l4_gpus() -> HashMap<String, u32> {+ HashMap::from([("l4-spot".to_string(), 1)])+ }++ fn limited_pool_manager(limits: PoolLimits) -> PoolManager {+ PoolManager::new(vec!["l4-spot".to_string()]).with_limits(limits)+ }++ fn limit_error(error: Box<dyn std::error::Error + Send + Sync>) -> PoolLimitError {+ match error.downcast::<PoolLimitError>() {+ Ok(limit) => *limit,+ Err(other) => panic!("expected a pool limit error, got {other}"),+ }+ }++ fn remote_pool(name: &str, ttl_seconds: Option<u64>, minimum_worker_count: u32) -> Pool {+ Pool {+ spec: PoolSpec {+ name: name.to_string(),+ queue_pool: DEFAULT_POOL_NAME.to_string(),+ bundle: None,+ gpus: l4_gpus(),+ gpu_caps: HashMap::new(),+ ttl_seconds,+ minimum_worker_count,+ pinned_models: Vec::new(),+ },+ status: PoolStatus {+ state: PoolState::Pending,+ assigned_workers: Vec::new(),+ created_at: PoolManager::now_secs(),+ last_renewed: PoolManager::now_secs(),+ },+ }+ }++ #[test]+ fn test_default_pool_limits_are_bounded() {+ let limits = PoolLimits::default();+ assert_eq!(limits.max_minimum_worker_count, 4);+ assert_eq!(limits.max_ttl_seconds, 3600);+ assert_eq!(limits.max_pools, 64);+ }++ #[tokio::test]+ async fn test_create_pool_rejects_minimum_worker_count_above_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 2,+ ..PoolLimits::default()+ });++ pm.create_pool("at-limit", l4_gpus(), None, None, 2, vec![])+ .await+ .expect("a floor at the limit is accepted");+ let error = pm+ .create_pool("above-limit", l4_gpus(), None, None, 3, vec![])+ .await+ .expect_err("a floor above the limit is rejected");++ assert_eq!(+ limit_error(error),+ PoolLimitError::MinimumWorkerCount {+ requested: 3,+ max: 2+ }+ );+ assert!(pm.get_pool("above-limit").await.is_none());+ }++ #[tokio::test]+ async fn test_update_cannot_raise_minimum_worker_count_above_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 2,+ ..PoolLimits::default()+ });+ pm.create_pool("bench", l4_gpus(), None, None, 1, vec![])+ .await+ .unwrap();++ let error = pm+ .create_pool("bench", l4_gpus(), None, None, 10, vec![])+ .await+ .expect_err("an update above the limit is rejected");++ assert!(matches!(+ limit_error(error),+ PoolLimitError::MinimumWorkerCount { .. }+ ));+ assert_eq!(+ pm.get_pool("bench")+ .await+ .unwrap()+ .spec+ .minimum_worker_count,+ 1+ );+ }++ #[tokio::test]+ async fn test_create_pool_rejects_gpu_requirement_above_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 4,+ ..PoolLimits::default()+ });++ pm.create_pool(+ "at-limit",+ HashMap::from([("l4-spot".to_string(), 4)]),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .expect("a requirement at the limit is accepted");+ let error = pm+ .create_pool(+ "eval",+ HashMap::from([("l4-spot".to_string(), 6)]),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .expect_err("a requirement above the limit is rejected");++ assert_eq!(+ limit_error(error),+ PoolLimitError::GpuRequirementTotal {+ requested: 6,+ max: 4+ }+ );+ assert!(pm.get_pool("eval").await.is_none());+ }++ fn profile_manager(profiles: usize) -> PoolManager {+ PoolManager::new((0..profiles).map(|index| format!("gpu-{index}")).collect())+ }++ fn zero_requirements(profiles: usize) -> HashMap<String, u32> {+ (0..profiles)+ .map(|index| (format!("gpu-{index}"), 0))+ .collect()+ }++ #[tokio::test]+ async fn test_warm_floor_budget_counts_every_machine_profile() {+ let pm = profile_manager(20);++ let error = pm+ .create_pool("fanout", zero_requirements(20), None, None, 4, vec![])+ .await+ .expect_err("a floor fanned out over 20 profiles exceeds the budget");+ assert_eq!(+ limit_error(error),+ PoolLimitError::WarmFloorTotal {+ minimum_worker_count: 4,+ profiles: 20,+ max: 4+ }+ );+ pm.create_pool("two-lanes", zero_requirements(2), None, None, 2, vec![])+ .await+ .expect("2 profiles x floor 2 fits the budget of 4");+ }++ #[tokio::test]+ async fn test_gpu_requirement_budget_is_summed_across_profiles() {+ let pm = profile_manager(3);+ let gpus: HashMap<String, u32> = (0..3).map(|index| (format!("gpu-{index}"), 2)).collect();++ let error = pm+ .create_pool("wide", gpus, None, None, 0, vec![])+ .await+ .expect_err("2 + 2 + 2 exceeds the budget of 4");+ assert_eq!(+ limit_error(error),+ PoolLimitError::GpuRequirementTotal {+ requested: 6,+ max: 4+ }+ );+ }++ #[tokio::test]+ async fn test_stored_pool_warm_floor_and_lease_fit_the_pool_budget() {+ let pm = PoolManager::new(Vec::new());+ let mut pool = remote_pool("legacy", None, 4);+ pool.spec.gpus = (0..8).map(|index| (format!("gpu-{index}"), 4)).collect();+ pool.status.assigned_workers = (0..8)+ .flat_map(|index| assigned(4, &format!("gpu-{index}")))+ .collect();+ pm.apply_remote_pool(pool).await;++ let (snapshot,) = {+ let snapshots = pm.capacity_pools().await;+ assert_eq!(snapshots.len(), 1);+ (snapshots.into_iter().next().unwrap(),)+ };+ assert_eq!(snapshot.minimum_worker_count, 1);+ assert_eq!(+ snapshot.machine_profiles,+ vec!["gpu-0", "gpu-1", "gpu-2", "gpu-3"]+ );+ assert_eq!(snapshot.assigned_workers.len(), 4);+ }++ #[tokio::test]+ async fn test_stored_pool_case_variant_profiles_share_one_allotment() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);+ let mut pool = remote_pool("legacy", None, 0);+ pool.spec.gpus = HashMap::from([("L4-SPOT".to_string(), 2), ("l4-spot".to_string(), 2)]);+ pm.apply_remote_pool(pool).await;+ let four: Vec<_> = (0..4)+ .map(|index| {+ worker(+ &format!("worker-{index}"),+ &format!("http://worker-{index}:8080"),+ "l4-spot",+ "default",+ )+ })+ .collect();++ assert!(pm.assign_workers("legacy", &four).await);+ assert_eq!(+ pm.get_pool("legacy").await.unwrap().status.state,+ PoolState::Active+ );+ assert_eq!(leased_counts(&pm).await.get("legacy"), Some(&4));+ }++ #[tokio::test]+ async fn test_stored_pool_floor_is_spread_over_lanes_within_the_budget() {+ let pm = PoolManager::new(Vec::new());+ let mut pool = remote_pool("legacy", None, 4);+ pool.spec.gpus = (0..3).map(|index| (format!("gpu-{index}"), 0)).collect();+ pm.apply_remote_pool(pool).await;++ let snapshot = pm.capacity_pools().await.into_iter().next().unwrap();++ assert_eq!(snapshot.minimum_worker_count, 1);+ assert_eq!(snapshot.machine_profiles.len(), 3);+ }++ #[tokio::test]+ async fn test_stored_pool_over_the_requirement_budget_stays_active_with_a_capped_lease() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);+ let mut pool = remote_pool("legacy", None, 0);+ pool.spec.gpus = HashMap::from([("l4-spot".to_string(), 6)]);+ pm.apply_remote_pool(pool).await;+ let four: Vec<_> = (0..4)+ .map(|index| {+ worker(+ &format!("worker-{index}"),+ &format!("http://worker-{index}:8080"),+ "l4-spot",+ "default",+ )+ })+ .collect();++ assert!(pm.assign_workers("legacy", &four).await);+ assert_eq!(+ pm.get_pool("legacy").await.unwrap().status.state,+ PoolState::Active+ );+ assert_eq!(leased_counts(&pm).await.get("legacy"), Some(&4));+ }++ #[tokio::test]+ async fn test_update_cannot_raise_gpu_requirement_above_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 4,+ ..PoolLimits::default()+ });+ pm.create_pool("eval", l4_gpus(), None, None, 0, vec![])+ .await+ .unwrap();++ let error = pm+ .create_pool(+ "eval",+ HashMap::from([("l4-spot".to_string(), 6)]),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .expect_err("an update above the limit is rejected");++ assert!(matches!(+ limit_error(error),+ PoolLimitError::GpuRequirementTotal { .. }+ ));+ assert_eq!(+ pm.get_pool("eval").await.unwrap().spec.gpus.get("l4-spot"),+ Some(&1)+ );+ }++ #[tokio::test]+ async fn test_pool_at_the_requirement_limit_stays_active_and_leased() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 4,+ ..PoolLimits::default()+ });+ pm.create_pool(+ "eval",+ HashMap::from([("l4-spot".to_string(), 4)]),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .unwrap();+ let workers: Vec<_> = (0..4)+ .map(|index| {+ worker(+ &format!("worker-{index}"),+ &format!("http://worker-{index}:8080"),+ "l4-spot",+ "default",+ )+ })+ .collect();++ assert!(pm.assign_workers("eval", &workers).await);+ assert_eq!(+ pm.get_pool("eval").await.unwrap().status.state,+ PoolState::Active+ );+ assert_eq!(leased_counts(&pm).await.get("eval"), Some(&4));+ }++ #[tokio::test]+ async fn test_create_pool_rejects_ttl_above_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_ttl_seconds: 600,+ ..PoolLimits::default()+ });++ pm.create_pool("at-limit", l4_gpus(), None, Some(600), 0, vec![])+ .await+ .expect("a TTL at the limit is accepted");+ let error = pm+ .create_pool("above-limit", l4_gpus(), None, Some(u64::MAX), 0, vec![])+ .await+ .expect_err("a TTL above the limit is rejected");++ assert_eq!(+ limit_error(error),+ PoolLimitError::Ttl {+ requested: u64::MAX,+ max: 600+ }+ );+ }++ #[tokio::test]+ async fn test_create_pool_enforces_live_pool_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_pools: 2,+ ..PoolLimits::default()+ });+ pm.create_default_pool().await;+ pm.sync_static_pools(&[static_queue_pool("company-a", "l4-spot")])+ .await+ .unwrap();+ pm.create_pool("first", l4_gpus(), None, None, 0, vec![])+ .await+ .unwrap();+ pm.create_pool("second", l4_gpus(), None, None, 0, vec![])+ .await+ .unwrap();++ let error = pm+ .create_pool("third", l4_gpus(), None, None, 0, vec![])+ .await+ .expect_err("a pool beyond the limit is rejected");+ assert_eq!(limit_error(error), PoolLimitError::TooManyPools { max: 2 });++ pm.create_pool("SECOND", l4_gpus(), None, Some(60), 0, vec![])+ .await+ .expect("updating an existing pool at the limit is allowed");++ pm.delete_pool("first").await.unwrap();+ pm.create_pool("third", l4_gpus(), None, None, 0, vec![])+ .await+ .expect("deleting a pool frees a slot");+ }++ #[tokio::test]+ async fn test_zero_pool_limit_disables_api_pools_but_keeps_default() {+ let pm = limited_pool_manager(PoolLimits {+ max_pools: 0,+ ..PoolLimits::default()+ });+ pm.create_default_pool().await;++ assert!(pm.get_pool(DEFAULT_POOL_NAME).await.is_some());+ let error = pm+ .create_pool("bench", l4_gpus(), None, None, 0, vec![])+ .await+ .expect_err("no API-created pool fits a zero limit");+ assert_eq!(limit_error(error), PoolLimitError::TooManyPools { max: 0 });+ }++ #[tokio::test]+ async fn test_stored_pool_lease_never_outlives_ttl_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_ttl_seconds: 60,+ ..PoolLimits::default()+ });+ pm.apply_remote_pool(remote_pool("legacy", Some(u64::from(u32::MAX)), 0))+ .await;+ {+ let mut pools = pm.pools.write().await;+ pools.get_mut("legacy").unwrap().status.last_renewed -= 61.0;+ }++ let expired = pm.check_expired_leases().await;++ assert_eq!(expired, vec!["legacy".to_string()]);+ assert!(pm.get_pool("legacy").await.is_none());+ }++ #[tokio::test]+ async fn test_ttl_limit_below_the_default_lease_also_caps_pools_without_ttl() {+ let pm = limited_pool_manager(PoolLimits {+ max_ttl_seconds: 600,+ ..PoolLimits::default()+ });+ pm.create_pool("no-ttl", l4_gpus(), None, None, 0, vec![])+ .await+ .unwrap();+ let pool = pm.get_pool("no-ttl").await.unwrap();+ assert_eq!(pm.lease_ttl_seconds(&pool), 600);+ {+ let mut pools = pm.pools.write().await;+ pools.get_mut("no-ttl").unwrap().status.last_renewed -= 601.0;+ }++ assert_eq!(pm.check_expired_leases().await, vec!["no-ttl".to_string()]);+ }++ #[tokio::test]+ async fn test_default_limits_keep_the_default_lease() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);+ pm.create_pool("no-ttl", l4_gpus(), None, None, 0, vec![])+ .await+ .unwrap();+ let pool = pm.get_pool("no-ttl").await.unwrap();++ assert_eq!(pm.lease_ttl_seconds(&pool), DEFAULT_LEASE_DURATION_S as i32);+ }++ fn assigned(count: usize, gpu: &str) -> Vec<AssignedWorker> {+ (0..count)+ .map(|index| AssignedWorker {+ name: format!("worker-{gpu}-{index}"),+ url: format!("http://worker-{gpu}-{index}:8080"),+ gpu: gpu.to_string(),+ bundle: "default".to_string(),+ })+ .collect()+ }++ async fn leased_counts(pm: &PoolManager) -> HashMap<String, usize> {+ pm.capacity_pools()+ .await+ .into_iter()+ .map(|pool| (pool.name, pool.assigned_workers.len()))+ .collect()+ }++ #[tokio::test]+ async fn test_zero_requirement_api_pool_leases_no_workers() {+ let pm = PoolManager::new(vec!["l4-spot".to_string()]);+ let mut pool = remote_pool("burst", None, 0);+ pool.spec.gpus = HashMap::from([("l4-spot".to_string(), 0)]);+ pool.status.state = PoolState::Active;+ pool.status.assigned_workers = assigned(10, "l4-spot");+ pm.apply_remote_pool(pool).await;++ assert_eq!(leased_counts(&pm).await.get("burst"), Some(&0));+ }++ #[tokio::test]+ async fn test_api_pool_lease_is_capped_by_requirement_and_limit() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 3,+ ..PoolLimits::default()+ });+ let mut small = remote_pool("small", None, 0);+ small.spec.gpus = HashMap::from([("L4-SPOT".to_string(), 2)]);+ small.status.assigned_workers = assigned(10, "l4-spot");+ let mut large = remote_pool("large", None, 0);+ large.spec.gpus = HashMap::from([("l4-spot".to_string(), 50)]);+ large.status.assigned_workers = assigned(10, "l4-spot");+ pm.apply_remote_pool(small).await;+ pm.apply_remote_pool(large).await;++ let counts = leased_counts(&pm).await;+ assert_eq!(counts.get("small"), Some(&2));+ assert_eq!(counts.get("large"), Some(&3));+ }++ #[tokio::test]+ async fn test_static_pool_lease_is_not_capped() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 1,+ ..PoolLimits::default()+ });+ pm.sync_static_pools(&[static_queue_pool("company-a", "l4-spot")])+ .await+ .unwrap();+ {+ let mut pools = pm.pools.write().await;+ pools.get_mut("company-a").unwrap().status.assigned_workers = assigned(5, "l4-spot");+ }++ assert_eq!(leased_counts(&pm).await.get("company-a"), Some(&5));+ }++ #[tokio::test]+ async fn test_capacity_view_caps_api_pool_warm_floor_only() {+ let pm = limited_pool_manager(PoolLimits {+ max_minimum_worker_count: 2,+ ..PoolLimits::default()+ });+ let mut static_pool = static_queue_pool("company-a", "l4-spot");+ static_pool.minimum_worker_count = 5;+ pm.sync_static_pools(&[static_pool]).await.unwrap();+ pm.apply_remote_pool(remote_pool("legacy", None, 10)).await;++ let floors: HashMap<String, u32> = pm+ .capacity_pools()+ .await+ .into_iter()+ .map(|pool| (pool.name, pool.minimum_worker_count))+ .collect();++ assert_eq!(floors.get("legacy"), Some(&2));+ assert_eq!(floors.get("company-a"), Some(&5));+ }}diff --git a/packages/sie_mcp/README.md b/packages/sie_mcp/README.mdindex b1e23b5fb..dbe41a213 100644--- a/packages/sie_mcp/README.md+++ b/packages/sie_mcp/README.md@@ -322,6 +322,10 @@ Enable the edge:Replace the example `v0.7.1` image tag below with the SIE release you wantto deploy.+The edge Ingress carries connector secrets and OAuth tokens, so the chart+requires TLS for it. This example issues the certificate with cert-manager+(installed in the cluster) and Let's Encrypt:+```bashhelm upgrade sie deploy/helm/sie-cluster -n sie --reuse-values \--set mcpEdge.enabled=true \@@ -330,9 +334,19 @@ helm upgrade sie deploy/helm/sie-cluster -n sie --reuse-values \--set mcpEdge.existingSecretName=sie-mcp-connector-secrets \--set mcpEdge.publicUrl=https://mcp.example.com \--set mcpEdge.ingress.enabled=true \- --set mcpEdge.ingress.host=mcp.example.com+ --set mcpEdge.ingress.host=mcp.example.com \+ --set ingress.tlsConfig.enabled=true \+ --set ingress.tlsConfig.mode=cert-manager \+ --set [email protected]```+To use a certificate you manage instead, create a `kubernetes.io/tls` Secret+named `<release fullname>-mcp-tls` (for example `sie-mcp-tls`) and set only+`ingress.tlsConfig.enabled=true`. When TLS terminates in front of the Ingress,+set `ingress.tlsConfig.mode=disabled`. `mcpEdge.ingress.allowPlaintext=true`+serves the edge over plain HTTP, which exposes connector secrets and OAuth+tokens on the network; use it only on a private network.+For an external gateway instead of the in-cluster gateway, add:```bashdiff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.mdindex 00cab38e1..f5f44b297 100644--- a/packages/sie_sdk/README.md+++ b/packages/sie_sdk/README.md@@ -254,6 +254,16 @@ client = SIEClient()```+When `base_url` is omitted, the client reads `SIE_BASE_URL`. When `api_key` is+omitted, it selects `SIE_API_KEY` only for a base URL with the same origin as+`SIE_BASE_URL`; a client for any other URL does not pick it up. Set both+variables to let code and integrations that construct a client without+credentials use a gateway with token auth. An explicit argument always wins;+`api_key=""` sends no credential. The `connections` namespace reuses the+client's key on requests to an explicitly configured `control_plane_url`, so a+client whose `control_plane_url` is on another origin must pass `api_key`+explicitly rather than rely on `SIE_API_KEY`.+## Generation execution evidence`SIEClient.last_model_revision` retains the `X-SIE-Model-Revision` responsediff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 0cc4ee99b..de293e22c 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport errnoimport loggingimport math+import osimport randomimport reimport socket@@ -143,6 +144,58 @@ def validate_base_url(base_url: str) -> None:raise ValueError(msg) from exc+SIE_BASE_URL_ENV = "SIE_BASE_URL"+SIE_API_KEY_ENV = "SIE_API_KEY"+++def resolve_base_url(base_url: str | None) -> str:+ """Return ``base_url``, or the ``SIE_BASE_URL`` environment variable when it is omitted."""+ if base_url is not None:+ return base_url+ env_base_url = os.environ.get(SIE_BASE_URL_ENV, "").strip()+ if not env_base_url:+ msg = f"base_url is required: pass it explicitly or set {SIE_BASE_URL_ENV}"+ raise ValueError(msg)+ return env_base_url+++def _url_origin(url: str) -> tuple[str, str, int] | None:+ try:+ parts = urlsplit(url)+ port = parts.port+ except ValueError:+ return None+ scheme = parts.scheme.lower()+ if scheme not in {"http", "https"} or not parts.hostname:+ return None+ return scheme, parts.hostname.lower(), port or (443 if scheme == "https" else 80)+++def resolve_api_key(api_key: str | None, base_url: str, control_plane_url: str | None = None) -> str | None:+ """Return ``api_key``, or ``SIE_API_KEY`` when it is omitted and ``base_url`` is the ``SIE_BASE_URL`` origin.++ An explicit value, including an empty string, always wins, so a caller can+ opt out of the environment credential. The environment key is scoped to+ the origin named by ``SIE_BASE_URL``: a client built for any other URL+ does not select it, and a client whose ``control_plane_url`` names another+ origin must pass its key explicitly, because connection requests reuse the+ client's key.+ """+ if api_key is not None:+ return api_key+ env_api_key = os.environ.get(SIE_API_KEY_ENV, "").strip()+ env_origin = _url_origin(os.environ.get(SIE_BASE_URL_ENV, "").strip())+ if not env_api_key or env_origin is None or _url_origin(base_url) != env_origin:+ return None+ if control_plane_url and _url_origin(control_plane_url) != env_origin:+ msg = (+ f"{SIE_API_KEY_ENV} is scoped to the {SIE_BASE_URL_ENV} origin and is not sent to "+ "control_plane_url on another origin; pass api_key explicitly"+ )+ raise ValueError(msg)+ return env_api_key++def url_origin_for_logging(url: str) -> str:"""Return only the ``scheme://host[:port]`` origin of ``url``.diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 7f076aa1d..b10049966 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -154,6 +154,8 @@ from ._shared import (raise_if_model_load_failed,read_timeout_message,request_matches_base_url_origin,+ resolve_api_key,+ resolve_base_url,resolve_timeouts,retry_after_or_default,settled_charge_from_usage,@@ -422,10 +424,16 @@ class SIEAsyncClient:Args:base_url: Base URL of the SIE server (e.g., "http://localhost:8080").+ Defaults to the ``SIE_BASE_URL`` environment variable when omitted.timeout_s: One per-attempt limit in seconds for both connecting andwaiting for response data. Sets ``connect_timeout_s`` and``read_timeout_s`` together; either of those overrides it.api_key: Optional API key for authentication (sent as Bearer token).+ When omitted, the ``SIE_API_KEY`` environment variable is used only if+ ``base_url`` has the same origin as ``SIE_BASE_URL`` (including when+ ``base_url`` itself comes from ``SIE_BASE_URL``); with a+ ``control_plane_url`` on another origin the key must be passed+ explicitly. Pass ``""`` to send no credential.gpu: GPU type for requests (e.g., "l4", "a100-80gb"). Can be overridden per-call.options: Options dict for requests. Merged with per-call options (per-call wins).pool: Resource pool spec for isolated capacity. Created lazily on first request.@@ -468,7 +476,7 @@ class SIEAsyncClient:def __init__(self,- base_url: str,+ base_url: str | None = None,*,timeout_s: float | None = None,api_key: str | None = None,@@ -483,6 +491,8 @@ class SIEAsyncClient:connect_timeout_s: float | None = None,read_timeout_s: float | None = None,) -> None:+ base_url = resolve_base_url(base_url)+ api_key = resolve_api_key(api_key, base_url, control_plane_url)# Normalize base_url (remove trailing slash)validate_base_url(base_url)self._base_url = base_url.rstrip("/")diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex d16cd3cb9..dcdd15e46 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -163,6 +163,8 @@ from ._shared import (raise_if_model_load_failed,read_timeout_message,request_matches_base_url_origin,+ resolve_api_key,+ resolve_base_url,resolve_timeouts,retry_after_or_default,settled_charge_from_usage,@@ -391,10 +393,16 @@ class SIEClient:Args:base_url: Base URL of the SIE server (e.g., "http://localhost:8080").+ Defaults to the ``SIE_BASE_URL`` environment variable when omitted.timeout_s: One per-attempt limit in seconds for both connecting andwaiting for response data. Sets ``connect_timeout_s`` and``read_timeout_s`` together; either of those overrides it.api_key: Optional API key for authentication (sent as Bearer token).+ When omitted, the ``SIE_API_KEY`` environment variable is used only if+ ``base_url`` has the same origin as ``SIE_BASE_URL`` (including when+ ``base_url`` itself comes from ``SIE_BASE_URL``); with a+ ``control_plane_url`` on another origin the key must be passed+ explicitly. Pass ``""`` to send no credential.gpu: Default GPU/machine profile for requests (e.g., "l4", "l4-spot").Can be overridden per-call.options: Options dict for requests. Merged with per-call options (per-call wins).@@ -440,7 +448,7 @@ class SIEClient:def __init__(self,- base_url: str,+ base_url: str | None = None,*,timeout_s: float | None = None,api_key: str | None = None,@@ -454,6 +462,8 @@ class SIEClient:connect_timeout_s: float | None = None,read_timeout_s: float | None = None,) -> None:+ base_url = resolve_base_url(base_url)+ api_key = resolve_api_key(api_key, base_url, control_plane_url)# Normalize base_url (remove trailing slash)validate_base_url(base_url)self._base_url = base_url.rstrip("/")diff --git a/packages/sie_sdk/tests/client/test_env_credentials.py b/packages/sie_sdk/tests/client/test_env_credentials.pynew file mode 100644index 000000000..4a411d0fb--- /dev/null+++ b/packages/sie_sdk/tests/client/test_env_credentials.py@@ -0,0 +1,229 @@+"""``SIE_BASE_URL`` and ``SIE_API_KEY`` fallbacks for both client constructors."""++from __future__ import annotations++from collections.abc import Iterator+from typing import Any+from unittest.mock import AsyncMock, patch++import pytest+from sie_sdk import SIEAsyncClient, SIEClient++[email protected](autouse=True)+def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("SIE_BASE_URL", raising=False)+ monkeypatch.delenv("SIE_API_KEY", raising=False)+++def sync_headers() -> Iterator[dict[str, Any]]:+ captured: dict[str, Any] = {}+ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:+ client_cls.side_effect = lambda **kwargs: captured.update(kwargs) or client_cls.return_value+ yield captured+++async def _async_session_kwargs(client: SIEAsyncClient) -> dict[str, Any]:+ with (+ patch("sie_sdk.client.async_.aiohttp.ClientSession") as session_cls,+ patch("sie_sdk.client.async_.aiohttp.TCPConnector"),+ ):+ session_cls.return_value.close = AsyncMock()+ client._ensure_session()+ kwargs = session_cls.call_args.kwargs+ await client.close()+ return kwargs+++def test_sync_client_reads_base_url_and_api_key_from_env(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]+) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com/")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ client = SIEClient()++ assert client.base_url == "https://gateway.example.com"+ assert sync_headers["base_url"] == "https://gateway.example.com"+ assert sync_headers["headers"]["Authorization"] == "Bearer env-key"+++def test_sync_client_explicit_arguments_win_over_env(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]+) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://env.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ client = SIEClient("http://localhost:8080", api_key="explicit-key")++ assert client.base_url == "http://localhost:8080"+ assert sync_headers["headers"]["Authorization"] == "Bearer explicit-key"+++ "base_url",+ ["https://gateway.example.com", "https://GATEWAY.example.com:443/v1", "https://gateway.example.com/"],+)+def test_sync_client_sends_env_key_to_the_env_base_url_origin(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any], base_url: str+) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ SIEClient(base_url)++ assert sync_headers["headers"]["Authorization"] == "Bearer env-key"+++ ("env_base_url", "base_url"),+ [+ (None, "https://gateway.example.com"),+ ("https://gateway.example.com", "https://other.example.com"),+ ("https://gateway.example.com", "http://gateway.example.com"),+ ("https://gateway.example.com", "https://gateway.example.com:8443"),+ ("not a url", "https://gateway.example.com"),+ ],+)+def test_sync_client_withholds_env_key_from_other_origins(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any], env_base_url: str | None, base_url: str+) -> None:+ if env_base_url is not None:+ monkeypatch.setenv("SIE_BASE_URL", env_base_url)+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ SIEClient(base_url)++ assert "Authorization" not in sync_headers["headers"]+++def test_clients_require_an_explicit_key_for_a_cross_origin_control_plane(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ with pytest.raises(ValueError, match="control_plane_url"):+ SIEClient(control_plane_url="https://control.example.com")+ with pytest.raises(ValueError, match="control_plane_url"):+ SIEAsyncClient(control_plane_url="https://control.example.com")+++def test_sync_client_keeps_env_key_for_a_same_origin_control_plane(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]+) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ SIEClient(control_plane_url="https://gateway.example.com/control")++ assert sync_headers["headers"]["Authorization"] == "Bearer env-key"+++async def test_clients_treat_an_empty_control_plane_url_as_none(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]+) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ SIEClient(control_plane_url="")+ async_kwargs = await _async_session_kwargs(SIEAsyncClient(control_plane_url=""))++ assert sync_headers["headers"]["Authorization"] == "Bearer env-key"+ assert async_kwargs["headers"]["Authorization"] == "Bearer env-key"+++def test_sync_client_explicit_key_may_go_to_a_cross_origin_control_plane(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]+) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ SIEClient(api_key="explicit-key", control_plane_url="https://control.example.com")++ assert sync_headers["headers"]["Authorization"] == "Bearer explicit-key"+++def test_sync_client_empty_api_key_opts_out_of_env_key(+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]+) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "http://localhost:8080")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ SIEClient("http://localhost:8080", api_key="")++ assert "Authorization" not in sync_headers["headers"]+++def test_sync_client_ignores_blank_env_key(monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "http://localhost:8080")+ monkeypatch.setenv("SIE_API_KEY", " ")++ SIEClient("http://localhost:8080")++ assert "Authorization" not in sync_headers["headers"]++[email protected]("env_value", [None, "", " "])+def test_clients_require_a_base_url(monkeypatch: pytest.MonkeyPatch, env_value: str | None) -> None:+ if env_value is not None:+ monkeypatch.setenv("SIE_BASE_URL", env_value)+ with pytest.raises(ValueError, match="SIE_BASE_URL"):+ SIEClient()+ with pytest.raises(ValueError, match="SIE_BASE_URL"):+ SIEAsyncClient()+++def test_clients_validate_the_env_base_url(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "localhost:8080")+ with pytest.raises(ValueError, match="http:// or https://"):+ SIEClient()+ with pytest.raises(ValueError, match="http:// or https://"):+ SIEAsyncClient()+++async def test_async_client_reads_base_url_and_api_key_from_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com/")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ client = SIEAsyncClient()+ kwargs = await _async_session_kwargs(client)++ assert client.base_url == "https://gateway.example.com"+ assert kwargs["base_url"] == "https://gateway.example.com"+ assert kwargs["headers"]["Authorization"] == "Bearer env-key"+++async def test_async_client_explicit_arguments_win_over_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://env.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ client = SIEAsyncClient("http://localhost:8080", api_key="explicit-key")+ kwargs = await _async_session_kwargs(client)++ assert client.base_url == "http://localhost:8080"+ assert kwargs["headers"]["Authorization"] == "Bearer explicit-key"+++async def test_async_client_scopes_env_key_to_the_env_base_url_origin(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ same_origin = await _async_session_kwargs(SIEAsyncClient("https://gateway.example.com/v1"))+ other_origin = await _async_session_kwargs(SIEAsyncClient("https://other.example.com"))++ assert same_origin["headers"]["Authorization"] == "Bearer env-key"+ assert "Authorization" not in other_origin["headers"]+++async def test_async_client_empty_api_key_opts_out_of_env_key(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_BASE_URL", "http://localhost:8080")+ monkeypatch.setenv("SIE_API_KEY", "env-key")++ kwargs = await _async_session_kwargs(SIEAsyncClient("http://localhost:8080", api_key=""))++ assert "Authorization" not in kwargs["headers"]diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.mdindex 35ef9cca4..b1497d90f 100644--- a/packages/sie_ts_sdk/README.md+++ b/packages/sie_ts_sdk/README.md@@ -24,6 +24,14 @@ const managed = new SIEClient("https://your-gateway.example.com", {});```+In Node.js, an omitted `baseUrl` falls back to `SIE_BASE_URL`. An omitted+`apiKey` selects `SIE_API_KEY` only for a base URL with the same origin as+`SIE_BASE_URL`; a client for any other URL does not pick it up. An explicit+value always wins; `apiKey: ""` sends no credential. The `connections`+namespace reuses the client's key on requests to an explicitly configured+`controlPlaneUrl`, so a client whose `controlPlaneUrl` is on another origin+must pass `apiKey` explicitly rather than rely on `SIE_API_KEY`.+> **Warning:** only pass `apiKey` in server-side code. Shipping it in a> browser bundle exposes the bearer key to anyone who loads the page.> For browser apps, route requests through a backend proxy that holdsdiff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 0c6228776..b7bd2e53b 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -336,6 +336,51 @@ function sleep(ms: number): Promise<void> {return new Promise((resolve) => setTimeout(resolve, ms));}+const SIE_BASE_URL_ENV = "SIE_BASE_URL";+const SIE_API_KEY_ENV = "SIE_API_KEY";++/**+ * Read a non-blank environment variable. Undefined outside Node-like runtimes+ * and where reading the environment is not permitted (Deno without --allow-env+ * throws).+ */+function readEnv(name: string): string | undefined {+ try {+ const value = globalThis.process?.env?.[name]?.trim();+ return value ? value : undefined;+ } catch {+ return undefined;+ }+}++function urlOrigin(url: string): string | undefined {+ try {+ const parsed = new URL(url);+ return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : undefined;+ } catch {+ return undefined;+ }+}++/**+ * `SIE_API_KEY`, scoped to the origin named by `SIE_BASE_URL`. Connection+ * requests reuse the client's key, so a control-plane URL on another origin+ * requires an explicit key.+ */+function envApiKeyFor(baseUrl: string, controlPlaneUrl: string | undefined): string | undefined {+ const apiKey = readEnv(SIE_API_KEY_ENV);+ const envOrigin = urlOrigin(readEnv(SIE_BASE_URL_ENV) ?? "");+ if (!apiKey || envOrigin === undefined || urlOrigin(baseUrl) !== envOrigin) {+ return undefined;+ }+ if (controlPlaneUrl && urlOrigin(controlPlaneUrl) !== envOrigin) {+ throw new TypeError(+ `${SIE_API_KEY_ENV} is scoped to the ${SIE_BASE_URL_ENV} origin and is not sent to controlPlaneUrl on another origin; pass apiKey explicitly.`,+ );+ }+ return apiKey;+}+const CONTENT_SAFE_MEDIA_TYPES = new Set(["application/json","application/problem+json",@@ -935,15 +980,20 @@ export class SIEClient {/*** Create a new SIE client.*- * @param baseUrl - Base URL of the SIE server (e.g., "http://localhost:8080")+ * @param baseUrl - Base URL of the SIE server (e.g., "http://localhost:8080").+ * Defaults to the `SIE_BASE_URL` environment variable when omitted.* @param options - Client options*/- constructor(baseUrl: string, options: SIEClientOptions = {}) {+ constructor(baseUrl?: string, options: SIEClientOptions = {}) {+ const url = baseUrl ?? readEnv(SIE_BASE_URL_ENV);+ if (url === undefined) {+ throw new TypeError(`baseUrl is required: pass it explicitly or set ${SIE_BASE_URL_ENV}.`);+ }// Validate eagerly: a scheme-less baseUrl ("localhost:8080") would// otherwise only surface at request time as a fetch `TypeError`.let parsed: URL | undefined;try {- parsed = new URL(baseUrl);+ parsed = new URL(url);} catch {parsed = undefined;}@@ -952,7 +1002,7 @@ export class SIEClient {// check while silently targeting the wrong host. Require a real// `scheme://<authority>`: `https?://` immediately followed by a non-slash// authority character.- const hasRealAuthority = /^https?:\/\/[^/]/i.test(baseUrl);+ const hasRealAuthority = /^https?:\/\/[^/]/i.test(url);if (!parsed ||(parsed.protocol !== "http:" && parsed.protocol !== "https:") ||@@ -960,16 +1010,16 @@ export class SIEClient {!hasRealAuthority) {throw new TypeError(- `Invalid baseUrl "${baseUrl}": must be an absolute http(s) URL with a host, e.g. "http://localhost:8080".`,+ `Invalid baseUrl "${url}": must be an absolute http(s) URL with a host, e.g. "http://localhost:8080".`,);}// Remove trailing slash- this.baseUrl = baseUrl.replace(/\/$/, "");+ this.baseUrl = url.replace(/\/$/, "");// `timeoutMs` is the unit-encoded name; `timeout` is a deprecated alias// for the same MILLISECONDS value. `timeoutMs` wins if both are set.this.timeout = options.timeoutMs ?? options.timeout ?? DEFAULT_TIMEOUT;this.gpu = options.gpu;- this.apiKey = options.apiKey;+ this.apiKey = options.apiKey ?? envApiKeyFor(this.baseUrl, options.controlPlaneUrl);// BREAKING CHANGE (0.7): default flipped from `false` to `true` to match// the Python SDK (`wait_for_capacity=True`). Callers that relied on// fail-fast 503 PROVISIONING / connect-error behaviour must now passdiff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex 3f8ebaf78..bad8bc002 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -763,7 +763,13 @@ export interface SIEClientOptions {timeout?: number;/** Default GPU type for all requests (e.g., "l4", "a100-80gb") */gpu?: string;- /** API key for authentication (sent as Bearer token) */+ /**+ * API key for authentication (sent as Bearer token). When omitted, the+ * `SIE_API_KEY` environment variable is used only if the base URL has the+ * same origin as `SIE_BASE_URL` (including when the base URL itself comes+ * from `SIE_BASE_URL`); with a `controlPlaneUrl` on another origin the key+ * must be passed explicitly. Pass `""` to send no credential.+ */apiKey?: string;/*** Default for whether the SDK waits out transient "no capacity yet"diff --git a/packages/sie_ts_sdk/tests/envCredentials.test.ts b/packages/sie_ts_sdk/tests/envCredentials.test.tsnew file mode 100644index 000000000..5fc4002a1--- /dev/null+++ b/packages/sie_ts_sdk/tests/envCredentials.test.ts@@ -0,0 +1,160 @@+/**+ * `SIE_BASE_URL` and `SIE_API_KEY` fallbacks for the client constructor.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { SIEClient } from "../src/client.js";+import { packMessage } from "../src/msgpack.js";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++async function encodeAuthorization(client: SIEClient): Promise<string | undefined> {+ mockFetch.mockResolvedValueOnce(+ new Response(packMessage({ items: [{ dense: { values: new Float32Array([0.1]) } }] }), {+ status: 200,+ headers: { "Content-Type": "application/msgpack" },+ }),+ );+ await client.encode("bge-m3", { text: "test" });+ const [url, init] = mockFetch.mock.calls[0] ?? [];+ expect(String(url).startsWith(client.getBaseUrl())).toBe(true);+ return (init?.headers as Record<string, string>).Authorization;+}++describe("SIEClient environment fallbacks", () => {+ beforeEach(() => {+ mockFetch.mockReset();+ vi.stubEnv("SIE_BASE_URL", "");+ vi.stubEnv("SIE_API_KEY", "");+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it("reads the base URL and API key from the environment", async () => {+ vi.stubEnv("SIE_BASE_URL", "https://gateway.example.test/");+ vi.stubEnv("SIE_API_KEY", "env-key");++ const client = new SIEClient();++ expect(client.getBaseUrl()).toBe("https://gateway.example.test");+ expect(await encodeAuthorization(client)).toBe("Bearer env-key");+ });++ it("prefers explicit arguments over the environment", async () => {+ vi.stubEnv("SIE_BASE_URL", "https://env.example.test");+ vi.stubEnv("SIE_API_KEY", "env-key");++ const client = new SIEClient("http://localhost:8080", { apiKey: "explicit-key" });++ expect(client.getBaseUrl()).toBe("http://localhost:8080");+ expect(await encodeAuthorization(client)).toBe("Bearer explicit-key");+ });++ it.each([+ "https://gateway.example.test",+ "https://GATEWAY.example.test:443/v1",+ "https://gateway.example.test/",+ ])("sends SIE_API_KEY to the SIE_BASE_URL origin (%s)", async (baseUrl) => {+ vi.stubEnv("SIE_BASE_URL", "https://gateway.example.test");+ vi.stubEnv("SIE_API_KEY", "env-key");++ expect(await encodeAuthorization(new SIEClient(baseUrl))).toBe("Bearer env-key");+ });++ it.each([+ ["", "https://gateway.example.test"],+ ["https://gateway.example.test", "https://other.example.test"],+ ["https://gateway.example.test", "http://gateway.example.test"],+ ["https://gateway.example.test", "https://gateway.example.test:8443"],+ ["not a url", "https://gateway.example.test"],+ ])(+ "withholds SIE_API_KEY when SIE_BASE_URL is %j and the base URL is %s",+ async (envBaseUrl, baseUrl) => {+ vi.stubEnv("SIE_BASE_URL", envBaseUrl);+ vi.stubEnv("SIE_API_KEY", "env-key");++ expect(await encodeAuthorization(new SIEClient(baseUrl))).toBeUndefined();+ },+ );++ it("requires an explicit key for a controlPlaneUrl on another origin", async () => {+ vi.stubEnv("SIE_BASE_URL", "https://gateway.example.test");+ vi.stubEnv("SIE_API_KEY", "env-key");++ expect(+ () => new SIEClient(undefined, { controlPlaneUrl: "https://control.example.test" }),+ ).toThrow(/controlPlaneUrl/);+ const sameOrigin = new SIEClient(undefined, {+ controlPlaneUrl: "https://gateway.example.test/control",+ });+ expect(await encodeAuthorization(sameOrigin)).toBe("Bearer env-key");+ mockFetch.mockReset();+ const explicit = new SIEClient(undefined, {+ apiKey: "explicit-key",+ controlPlaneUrl: "https://control.example.test",+ });+ expect(await encodeAuthorization(explicit)).toBe("Bearer explicit-key");+ });++ it("treats an empty controlPlaneUrl as no control plane", async () => {+ vi.stubEnv("SIE_BASE_URL", "https://gateway.example.test");+ vi.stubEnv("SIE_API_KEY", "env-key");++ const client = new SIEClient(undefined, { controlPlaneUrl: "" });++ expect(await encodeAuthorization(client)).toBe("Bearer env-key");+ });++ it("treats an unreadable environment as unset", () => {+ const original = globalThis.process.env;+ Object.defineProperty(globalThis.process, "env", {+ configurable: true,+ get() {+ throw new Error("env access denied");+ },+ });+ try {+ expect(() => new SIEClient()).toThrow(/SIE_BASE_URL/);+ expect(new SIEClient("http://localhost:8080").getBaseUrl()).toBe("http://localhost:8080");+ } finally {+ Object.defineProperty(globalThis.process, "env", {+ configurable: true,+ value: original,+ writable: true,+ });+ }+ });++ it("sends no credential when apiKey is an explicit empty string", async () => {+ vi.stubEnv("SIE_BASE_URL", "http://localhost:8080");+ vi.stubEnv("SIE_API_KEY", "env-key");++ const client = new SIEClient("http://localhost:8080", { apiKey: "" });++ expect(await encodeAuthorization(client)).toBeUndefined();+ });++ it("ignores a blank SIE_API_KEY", async () => {+ vi.stubEnv("SIE_BASE_URL", "http://localhost:8080");+ vi.stubEnv("SIE_API_KEY", " ");++ const client = new SIEClient("http://localhost:8080");++ expect(await encodeAuthorization(client)).toBeUndefined();+ });++ it("requires a base URL when SIE_BASE_URL is unset or blank", () => {+ expect(() => new SIEClient()).toThrow(/SIE_BASE_URL/);+ vi.stubEnv("SIE_BASE_URL", " ");+ expect(() => new SIEClient()).toThrow(/SIE_BASE_URL/);+ });++ it("validates the base URL read from the environment", () => {+ vi.stubEnv("SIE_BASE_URL", "localhost:8080");++ expect(() => new SIEClient()).toThrow(/must be an absolute http\(s\) URL/);+ });+});diff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.pyindex f4e0fbcbd..44ec7dd62 100644--- a/tools/ci/tests/test_helm_render.py+++ b/tools/ci/tests/test_helm_render.py@@ -209,9 +209,10 @@ def test_dashboards_cover_public_prometheus_metrics(tmp_path: Path) -> None:)-def render_chart(tmp_path: Path, values: dict) -> subprocess.CompletedProcess[str]:+def render_chart(tmp_path: Path, values: dict, overlays: tuple[str, ...] = ()) -> subprocess.CompletedProcess[str]:values_file = tmp_path / "chart-values.yaml"values_file.write_text(yaml.safe_dump(values), encoding="utf-8")+ overlay_args = [arg for overlay in overlays for arg in ("-f", str(helm.CHART_DIR / overlay))]return subprocess.run(["mise",@@ -223,6 +224,7 @@ def render_chart(tmp_path: Path, values: dict) -> subprocess.CompletedProcess[ststr(helm.CHART_DIR),"--namespace","sie",+ *(helm.validation_args(overlay_args) if overlays else []),"-f",str(values_file),],@@ -233,8 +235,8 @@ def render_chart(tmp_path: Path, values: dict) -> subprocess.CompletedProcess[st)-def rendered_documents(tmp_path: Path, values: dict) -> list[dict]:- result = render_chart(tmp_path, values)+def rendered_documents(tmp_path: Path, values: dict, overlays: tuple[str, ...] = ()) -> list[dict]:+ result = render_chart(tmp_path, values, overlays)assert result.returncode == 0, result.stderrreturn [doc for doc in yaml.safe_load_all(result.stdout) if doc]@@ -343,7 +345,8 @@ def test_operator_read_token_secret_is_used_unchanged(tmp_path: Path) -> None:def test_gateway_admin_token_is_wired_only_to_the_gateway(tmp_path: Path) -> None:- values = {**L4_POOL, "gateway": {"auth": {"mode": "token", "adminTokenSecretName": "gateway-admin"}}}+ auth = {"mode": "token", "tokenSecretName": "gateway-tokens", "adminTokenSecretName": "gateway-admin"}+ values = {**L4_POOL, "gateway": {"auth": auth}}docs = rendered_documents(tmp_path, values)assert env_entries(docs, "SIE_ADMIN_TOKEN") == {CONFIG_SERVICE: GENERATED_ADMIN,@@ -567,3 +570,477 @@ def test_reused_token_must_exist_and_have_at_least_32_characters(else:assert result.returncode != 0assert error.format(setting=setting) in result.stderr+++INGRESS_GUARD = "Refusing to render the gateway Ingress"+CLOUD_PRESETS = ["values-aws.yaml", "values-gke.yaml", "values-aks.yaml", "values-ack.yaml"]+++def gateway_ingresses(documents: list[dict]) -> list[dict]:+ return [+ doc+ for doc in documents+ if doc["kind"] == "Ingress"+ and any(+ path["backend"]["service"]["name"].endswith("-gateway")+ for rule in doc["spec"]["rules"]+ for path in rule["http"]["paths"]+ )+ ]+++def worker_network_policies(documents: list[dict]) -> list[dict]:+ return [+ doc+ for doc in documents+ if doc["kind"] == "NetworkPolicy" and doc["metadata"]["labels"].get("app.kubernetes.io/component") == "worker"+ ]++[email protected]("preset", CLOUD_PRESETS)+def test_cloud_presets_do_not_publish_an_ingress(tmp_path: Path, preset: str) -> None:+ assert gateway_ingresses(rendered_documents(tmp_path, {}, (preset,))) == []+++AUTH_GUARD = f"{INGRESS_GUARD}: nothing authenticates its requests"+TLS_GUARD = f"{INGRESS_GUARD} without TLS"+GATEWAY_AUTH = {"auth": {"mode": "static", "tokenSecretName": "sie-gateway-auth"}}+SCOPED_TLS = {"hosts": ["sie.example.com"], "tlsConfig": {"enabled": True, "mode": "byo", "secretName": "sie-tls"}}+UPSTREAM_TLS = {"hosts": ["sie.example.com"], "tlsConfig": {"enabled": False, "mode": "disabled"}}+OAUTH2_EDGE = {"enabled": True, "oauth2Proxy": {"oidcIssuerUrl": "https://issuer.example.com"}}+++def ingress_values(ingress: dict | None = None, **values: dict) -> dict:+ return {**values, "ingress": {"enabled": True, **(ingress or {})}}+++def render_error(tmp_path: Path, values: dict, overlays: tuple[str, ...] = ()) -> str:+ result = render_chart(tmp_path, values, overlays)+ assert result.returncode != 0, "render unexpectedly succeeded"+ return result.stderr++[email protected]("preset", CLOUD_PRESETS)+def test_enabling_an_ingress_on_a_preset_requires_authentication(tmp_path: Path, preset: str) -> None:+ assert AUTH_GUARD in render_error(tmp_path, ingress_values(), (preset,))++[email protected]("ingress", [{}, SCOPED_TLS, UPSTREAM_TLS, {"allowPlaintext": True}])+def test_unauthenticated_ingress_fails_whatever_its_host_and_tls(tmp_path: Path, ingress: dict) -> None:+ stderr = render_error(tmp_path, ingress_values(ingress))+ assert AUTH_GUARD in stderr+ assert "A hostname or TLS is not access control" in stderr+ assert "ingress.allowUnauthenticated=true" in stderr+++ "values",+ [+ {"gateway": GATEWAY_AUTH},+ {"gateway": {"auth": {"mode": "token", "tokenSecretName": "sie-gateway-auth"}}},+ {"auth": OAUTH2_EDGE},+ {"ingress": {"allowUnauthenticated": True}},+ ],+)+def test_authenticated_ingress_without_tls_fails(tmp_path: Path, values: dict) -> None:+ values = {**values, "ingress": {"enabled": True, **values.get("ingress", {})}}+ stderr = render_error(tmp_path, values)+ assert TLS_GUARD in stderr+ assert "ingress.allowPlaintext=true" in stderr+++ "ingress",+ [+ SCOPED_TLS,+ {"host": "sie.example.com", "tls": {"enabled": True}},+ UPSTREAM_TLS,+ {"allowPlaintext": True},+ ],+)+def test_authenticated_ingress_renders_with_tls_or_the_plaintext_opt_in(tmp_path: Path, ingress: dict) -> None:+ assert len(gateway_ingresses(rendered_documents(tmp_path, ingress_values(ingress, gateway=GATEWAY_AUTH)))) == 1+++def test_tls_without_a_host_does_not_count_as_tls(tmp_path: Path) -> None:+ values = ingress_values({"tlsConfig": {"enabled": True, "mode": "byo"}}, gateway=GATEWAY_AUTH)+ assert TLS_GUARD in render_error(tmp_path, values)+++def test_both_opt_ins_keep_the_previous_catch_all_ingress(tmp_path: Path) -> None:+ values = ingress_values({"allowUnauthenticated": True, "allowPlaintext": True})+ (ingress,) = gateway_ingresses(rendered_documents(tmp_path, values))+ assert [rule.get("host") for rule in ingress["spec"]["rules"]] == [None]+ assert "tls" not in ingress["spec"]+++def test_scoped_ingress_keeps_its_host_and_tls(tmp_path: Path) -> None:+ (ingress,) = gateway_ingresses(rendered_documents(tmp_path, ingress_values(SCOPED_TLS, gateway=GATEWAY_AUTH)))+ assert [rule["host"] for rule in ingress["spec"]["rules"]] == ["sie.example.com"]+ assert ingress["spec"]["tls"] == [{"hosts": ["sie.example.com"], "secretName": "sie-tls"}]++[email protected]("field", ["allowUnauthenticated", "allowPlaintext"])[email protected]("value", ["false", "true", 1])+def test_ingress_opt_ins_accept_only_booleans(tmp_path: Path, field: str, value: object) -> None:+ stderr = render_error(tmp_path, ingress_values({field: value, **SCOPED_TLS}, gateway=GATEWAY_AUTH))+ assert f"ingress.{field} must be a boolean" in stderr++[email protected]("class_name", ["alb", "traefik", "nginx-internal", ""])+def test_offline_render_credits_the_oauth2_edge_only_for_class_nginx(tmp_path: Path, class_name: str) -> None:+ values = ingress_values({"className": class_name, **SCOPED_TLS}, auth=OAUTH2_EDGE)+ stderr = render_error(tmp_path, values)+ assert "cannot inspect IngressClasses" in stderr+ assert "accepts only ingress.className=nginx" in stderr+++def test_oauth2_edge_on_ingress_nginx_counts_as_authentication(tmp_path: Path) -> None:+ values = ingress_values({"className": "nginx", **SCOPED_TLS}, auth=OAUTH2_EDGE)+ (ingress,) = gateway_ingresses(rendered_documents(tmp_path, values))+ assert "nginx.ingress.kubernetes.io/auth-url" in ingress["metadata"]["annotations"]+++ "extra_env",+ [+ [{"name": "SIE_AUTH_MODE", "value": "none"}, {"name": "SIE_AUTH_TOKEN", "value": ""}],+ [{"name": "SIE_AUTH_MODE", "valueFrom": {"configMapKeyRef": {"name": "gateway-auth", "key": "mode"}}}],+ ],+)+def test_extra_env_auth_mode_override_is_not_credited(tmp_path: Path, extra_env: list[dict]) -> None:+ values = ingress_values(SCOPED_TLS, gateway={**GATEWAY_AUTH, "extraEnv": extra_env})+ assert AUTH_GUARD in render_error(tmp_path, values)+++def test_extra_env_auth_mode_enabling_auth_is_credited(tmp_path: Path) -> None:+ extra_env = [+ {"name": "SIE_AUTH_MODE", "value": "token"},+ {"name": "SIE_AUTH_TOKENS", "valueFrom": {"secretKeyRef": {"name": "gateway-auth", "key": "tokens"}}},+ ]+ values = ingress_values(SCOPED_TLS, gateway={"extraEnv": extra_env})+ assert len(gateway_ingresses(rendered_documents(tmp_path, values))) == 1++[email protected]("mode", ["Static", "static ", "bearer"])+def test_unsupported_gateway_auth_mode_fails(tmp_path: Path, mode: str) -> None:+ stderr = render_error(tmp_path, {"gateway": {"auth": {"mode": mode, "tokenSecretName": "sie-gateway-auth"}}})+ assert "is not supported" in stderr++[email protected]("mode", ["static", "token"])+def test_gateway_token_auth_needs_a_token_source(tmp_path: Path, mode: str) -> None:+ assert "needs tokens" in render_error(tmp_path, {"gateway": {"auth": {"mode": mode}}})++[email protected]("service_type", ["LoadBalancer", "NodePort"])+def test_external_gateway_service_requires_auth_or_opt_in(tmp_path: Path, service_type: str) -> None:+ stderr = render_error(tmp_path, {"gateway": {"service": {"type": service_type, "allowPlaintext": True}}})+ assert f"Refusing to render gateway.service.type={service_type} without gateway auth" in stderr+ service = {"type": service_type, "allowPlaintext": True}+ rendered_documents(tmp_path, {"gateway": {**GATEWAY_AUTH, "service": service}})+ rendered_documents(tmp_path, {"gateway": {"service": {**service, "allowUnauthenticated": True}}})++[email protected]("service_type", ["LoadBalancer", "NodePort"])+def test_external_gateway_service_requires_a_plaintext_acknowledgement(tmp_path: Path, service_type: str) -> None:+ stderr = render_error(tmp_path, {"gateway": {**GATEWAY_AUTH, "service": {"type": service_type}}})+ assert f"Refusing to render gateway.service.type={service_type} without an explicit TLS decision" in stderr+ assert "gateway.service.allowPlaintext=true" in stderr++[email protected]("field", ["allowUnauthenticated", "allowPlaintext"])+def test_gateway_service_opt_ins_accept_only_booleans(tmp_path: Path, field: str) -> None:+ service = {"type": "LoadBalancer", "allowUnauthenticated": True, "allowPlaintext": True, field: "false"}+ assert f"gateway.service.{field} must be a boolean" in render_error(tmp_path, {"gateway": {"service": service}})+++def test_token_secret_without_token_auth_fails(tmp_path: Path) -> None:+ stderr = render_error(tmp_path, {"gateway": {"auth": {"mode": "none", "tokenSecretName": "sie-gateway-auth"}}})+ assert "gateway.auth.tokenSecretName is set but gateway auth mode is none" in stderr+++def test_ip_only_self_signed_certificate_is_not_ingress_tls(tmp_path: Path) -> None:+ ingress = {+ "tlsConfig": {"enabled": True, "mode": "self-signed", "selfSigned": {"leaf": {"ipAddresses": ["10.0.0.10"]}}}+ }+ stderr = render_error(tmp_path, ingress_values(ingress, gateway=GATEWAY_AUTH))+ assert TLS_GUARD in stderr+ assert "IP-only self-signed certificate is not supported" in stderr+++MCP_EDGE = {"enabled": True, "ingress": {"enabled": True, "host": "mcp.example.com"}}+++def mcp_edge_ingresses(documents: list[dict]) -> list[dict]:+ return [+ doc+ for doc in documents+ if doc["kind"] == "Ingress" and doc["metadata"]["labels"].get("app.kubernetes.io/component") == "mcp-edge"+ ]+++def test_mcp_edge_ingress_without_tls_fails(tmp_path: Path) -> None:+ stderr = render_error(tmp_path, {"mcpEdge": MCP_EDGE})+ assert "Refusing to render the MCP edge Ingress without TLS" in stderr+ assert "mcpEdge.ingress.allowPlaintext=true" in stderr+++ "values",+ [+ {"ingress": {"tlsConfig": {"enabled": True, "mode": "byo"}}},+ {"ingress": {"tlsConfig": {"enabled": False, "mode": "disabled"}}},+ {"mcpEdge": {"ingress": {"allowPlaintext": True}}},+ ],+)+def test_mcp_edge_ingress_renders_with_tls_or_the_plaintext_opt_in(tmp_path: Path, values: dict) -> None:+ mcp_edge = {**MCP_EDGE, "ingress": {**MCP_EDGE["ingress"], **values.get("mcpEdge", {}).get("ingress", {})}}+ documents = rendered_documents(tmp_path, {**values, "mcpEdge": mcp_edge})+ assert len(mcp_edge_ingresses(documents)) == 1+++def test_mcp_edge_ingress_refuses_self_signed_mode_without_its_certificate(tmp_path: Path) -> None:+ tls = {"enabled": True, "mode": "self-signed", "selfSigned": {"leaf": {"dnsNames": ["mcp.example.com"]}}}+ stderr = render_error(tmp_path, {"mcpEdge": MCP_EDGE, "ingress": {"tlsConfig": tls}})+ assert "nothing issues the MCP edge certificate" in stderr+++def test_mcp_edge_plaintext_opt_in_accepts_only_booleans(tmp_path: Path) -> None:+ mcp_edge = {**MCP_EDGE, "ingress": {**MCP_EDGE["ingress"], "allowPlaintext": "false"}}+ assert "mcpEdge.ingress.allowPlaintext must be a boolean" in render_error(tmp_path, {"mcpEdge": mcp_edge})++[email protected]("service_type", ["LoadBalancer", "NodePort"])+def test_config_service_must_stay_cluster_ip(tmp_path: Path, service_type: str) -> None:+ stderr = render_error(tmp_path, {"config": {"service": {"type": service_type}}})+ assert f"config.service.type={service_type} is not supported" in stderr+++def test_worker_network_policy_is_off_by_default(tmp_path: Path) -> None:+ assert (+ worker_network_policies(rendered_documents(tmp_path, {"workers": {"pools": {"l4": {"enabled": True}}}})) == []+ )+++def test_ha_overlay_admits_only_gateway_pods_to_every_worker_port(tmp_path: Path) -> None:+ values = {"workers": {"pools": {"l4": {"enabled": True, "gpu": {"count": 2}}}}}+ documents = rendered_documents(tmp_path, values, ("values-aws.yaml", "values-ha.yaml"))+ (policy,) = worker_network_policies(documents)+ (gateway,) = [+ doc+ for doc in documents+ if doc["kind"] == "Deployment" and doc["metadata"]["labels"].get("app.kubernetes.io/component") == "gateway"+ ]+ workers = [+ doc for doc in documents if doc["kind"] == "StatefulSet" and doc["metadata"]["name"].startswith("sie-worker-")+ ]+ assert workers+ selector = policy["spec"]["podSelector"]["matchLabels"]+ for worker in workers:+ pod_labels = worker["spec"]["template"]["metadata"]["labels"]+ assert selector.items() <= pod_labels.items()+ worker_ports = {+ port["containerPort"]+ for worker in workers+ for container in worker["spec"]["template"]["spec"]["containers"]+ if container["name"] != "worker-sidecar"+ for port in container.get("ports", [])+ }+ assert policy["spec"]["policyTypes"] == ["Ingress"]+ (rule,) = policy["spec"]["ingress"]+ (peer,) = rule["from"]+ assert peer["podSelector"]["matchLabels"].items() <= gateway["spec"]["template"]["metadata"]["labels"].items()+ assert {port["port"] for port in rule["ports"]} == worker_ports == {8080, 8081}+++def test_worker_network_policy_appends_extra_ingress_rules(tmp_path: Path) -> None:+ extra = {+ "from": [{"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "bench"}}}],+ "ports": [{"port": 8080, "protocol": "TCP"}],+ }+ values = {+ "workers": {+ "networkPolicy": {"enabled": True, "extraIngress": [extra]},+ "pools": {"l4": {"enabled": True}},+ }+ }+ (policy,) = worker_network_policies(rendered_documents(tmp_path, values))+ assert policy["spec"]["ingress"][1] == extra+++ "rule",+ [+ {"from": [{"namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "bench"}}}]},+ {"ports": [{"port": 8080, "protocol": "TCP"}]},+ ],+)+def test_worker_network_policy_rejects_rules_without_from_or_ports(tmp_path: Path, rule: dict) -> None:+ values = {+ "workers": {"networkPolicy": {"enabled": True, "extraIngress": [rule]}, "pools": {"l4": {"enabled": True}}}+ }+ assert "workers.networkPolicy.extraIngress[0] needs a non-empty from and ports" in render_error(tmp_path, values)+++ ("rule", "message"),+ [+ ({"from": [{}], "ports": [{"port": 8080}]}, "extraIngress[0].from[0] admits every source"),+ (+ {"from": [{"namespaceSelector": {}}], "ports": [{"port": 8080}]},+ "extraIngress[0].from[0] admits every source",+ ),+ (+ {"from": [{"namespaceSelector": {"matchLabels": {"team": "bench"}}}], "ports": [{"protocol": "TCP"}]},+ "extraIngress[0].ports[0] admits every port",+ ),+ ],+)+def test_worker_network_policy_rejects_wildcard_peers_and_ports(tmp_path: Path, rule: dict, message: str) -> None:+ values = {+ "workers": {"networkPolicy": {"enabled": True, "extraIngress": [rule]}, "pools": {"l4": {"enabled": True}}}+ }+ assert message in render_error(tmp_path, values)+++ ("rule", "message"),+ [+ ({"from": [{"ipBlock": {"cidr": "0.0.0.0/0"}}], "ports": [{"port": 8080}]}, "admits every address"),+ ({"from": [{"ipBlock": {"cidr": "::/0"}}], "ports": [{"port": 8080}]}, "admits every address"),+ (+ {"from": [{"ipBlock": {"cidr": "10.0.0.0/8"}}], "ports": [{"port": 1, "endPort": 65535}]},+ "spans nearly every port",+ ),+ ],+)+def test_worker_network_policy_rejects_full_range_sources_and_ports(tmp_path: Path, rule: dict, message: str) -> None:+ values = {+ "workers": {"networkPolicy": {"enabled": True, "extraIngress": [rule]}, "pools": {"l4": {"enabled": True}}}+ }+ assert message in render_error(tmp_path, values)+++def test_worker_network_policy_accepts_a_scoped_ip_block_and_port_range(tmp_path: Path) -> None:+ rule = {+ "from": [{"ipBlock": {"cidr": "10.0.0.0/8"}}],+ "ports": [{"port": 8080, "endPort": 8081, "protocol": "TCP"}],+ }+ values = {+ "workers": {"networkPolicy": {"enabled": True, "extraIngress": [rule]}, "pools": {"l4": {"enabled": True}}}+ }+ (policy,) = worker_network_policies(rendered_documents(tmp_path, values))+ assert policy["spec"]["ingress"][1] == rule+++INGRESS_CLASS_LOOKUP = 'lookup "networking.k8s.io/v1" "IngressClass" "" ""'+++def ingress_class(name: str, controller: str, default: bool = False) -> dict:+ annotations = {"ingressclass.kubernetes.io/is-default-class": "true"} if default else {}+ return {"metadata": {"name": name, "annotations": annotations}, "spec": {"controller": controller}}+++def render_with_ingress_classes(tmp_path: Path, values: dict, classes: list[dict]) -> subprocess.CompletedProcess[str]:+ chart = tmp_path / "chart"+ shutil.copytree(ROOT / helm.CHART_DIR, chart, symlinks=True)+ helpers = chart / "templates" / "_helpers.tpl"+ source = helpers.read_text(encoding="utf-8")+ assert source.count(INGRESS_CLASS_LOOKUP) == 1+ helpers.write_text(+ source.replace(INGRESS_CLASS_LOOKUP, "(default (dict) .Values.ingressClassFixture)"), encoding="utf-8"+ )+ values_file = tmp_path / "overrides.yaml"+ values_file.write_text(yaml.safe_dump({**values, "ingressClassFixture": {"items": classes}}), encoding="utf-8")+ return subprocess.run(+ [+ "mise",+ "exec",+ "--",+ "helm",+ "template",+ "sie",+ str(chart),+ "--namespace",+ "sie",+ *helm.validation_args(["-f", str(values_file)]),+ ],+ cwd=ROOT,+ capture_output=True,+ text=True,+ check=False,+ )+++INGRESS_NGINX = "k8s.io/ingress-nginx"+NGINX_INC = "nginx.org/ingress-controller"+++ ("class_name", "classes", "message"),+ [+ (+ "",+ [ingress_class("a-f5", NGINX_INC, default=True), ingress_class("z-nginx", INGRESS_NGINX, default=True)],+ 'IngressClass "a-f5" (a default IngressClass',+ ),+ ("nginx", [ingress_class("nginx", NGINX_INC)], 'IngressClass "nginx" uses controller "nginx.org'),+ ("missing", [ingress_class("nginx", INGRESS_NGINX)], 'no IngressClass named "missing"'),+ ("", [ingress_class("nginx", INGRESS_NGINX)], "no IngressClass is marked as the cluster default"),+ (+ "internal",+ [ingress_class("internal", "k8s.io/internal-ingress-nginx")],+ "not in auth.ingress.acceptedControllers",+ ),+ ],+)+def test_oauth2_edge_rejects_ingress_classes_without_an_accepted_controller(+ tmp_path: Path, class_name: str, classes: list[dict], message: str+) -> None:+ values = ingress_values({"className": class_name, **SCOPED_TLS}, auth=OAUTH2_EDGE)+ result = render_with_ingress_classes(tmp_path, values, classes)+ assert result.returncode != 0+ assert message in result.stderr+++ ("class_name", "classes", "accepted"),+ [+ ("", [ingress_class("a", INGRESS_NGINX, default=True), ingress_class("b", INGRESS_NGINX, default=True)], None),+ ("nginx-internal", [ingress_class("nginx-internal", INGRESS_NGINX)], None),+ (+ "internal",+ [ingress_class("internal", "k8s.io/internal-ingress-nginx")],+ [INGRESS_NGINX, "k8s.io/internal-ingress-nginx"],+ ),+ ],+)+def test_oauth2_edge_accepts_ingress_classes_with_an_accepted_controller(+ tmp_path: Path, class_name: str, classes: list[dict], accepted: list[str] | None+) -> None:+ auth = {**OAUTH2_EDGE, **({"ingress": {"acceptedControllers": accepted}} if accepted else {})}+ values = ingress_values({"className": class_name, **SCOPED_TLS}, auth=auth)+ result = render_with_ingress_classes(tmp_path, values, classes)+ assert result.returncode == 0, result.stderr+ assert len(gateway_ingresses([doc for doc in yaml.safe_load_all(result.stdout) if doc])) == 1+++ ("rule", "message"),+ [+ ({"from": [{"ipBlock": {"cidr": "0::/0"}}], "ports": [{"port": 8080}]}, "admits every address"),+ ({"from": [{"ipBlock": {"cidr": "1.2.3.4/0"}}], "ports": [{"port": 8080}]}, "admits every address"),+ (+ {"from": [{"ipBlock": {"cidr": "10.0.0.0/8"}}], "ports": [{"port": 2, "endPort": 65535}]},+ "spans nearly every port",+ ),+ ],+)+def test_worker_network_policy_rejects_prefix_zero_and_near_full_port_ranges(+ tmp_path: Path, rule: dict, message: str+) -> None:+ values = {+ "workers": {"networkPolicy": {"enabled": True, "extraIngress": [rule]}, "pools": {"l4": {"enabled": True}}}+ }+ assert message in render_error(tmp_path, values)