Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(helm): generate gateway and worker tokens behind default-off values (#750)

Krisztian Gajdar2e6350e8e3e8
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.md
index 3b2eecfd7..8b7f97852 100644
--- a/deploy/helm/sie-cluster/README.md
+++ b/deploy/helm/sie-cluster/README.md
@@ -816,9 +816,11 @@ Below, `<fullname>` is the chart's full name: `<release>-sie-cluster`, or
reaches it. The chart owns `SIE_UPSTREAMS_FILE`, `SIE_REMOTE_SERVING` and
the credential variables, so `extraEnv` cannot set them, and an `extraEnv`
entry that reads an upstream's Secret anywhere else fails the render. An
- upstream's Secret key must also differ from every Secret key the chart
- hands to another component (the Hugging Face token, the gateway tokens, the
- sie-config tokens and the NATS passwords).
+ upstream's Secret key must also differ from the checked credential keys
+ listed in [Gateway token](#gateway-token), including the Hugging Face token,
+ gateway tokens, sie-config tokens, NATS passwords, and bundled Grafana admin
+ credentials. Optional dependency and arbitrary subchart configuration outside
+ that list needs operator separation; see [#767](https://github.com/superlinked/sie/issues/767).
- sie-config receives the upstream names (`SIE_UPSTREAM_NAMES`), built from the
same `upstreams` values as the remote lanes' file, and refuses with a `422` a
model whose remote profile names any other upstream. Without a remote lane it
@@ -869,9 +871,12 @@ A remote lane needs this policy or `workers.networkPolicy`, and the render
fails when both are off. The policy takes effect only with a CNI that enforces
NetworkPolicy.
-- **Ingress:** only this release's gateway pods, on the worker ports. The worker
- API has no authentication of its own, so without this rule any pod in the
- cluster could call a remote lane directly and spend its upstream credentials.
+- **Ingress:** this release's gateway pods, on the worker ports, and, while the
+ workers require the worker token, the release-time worker token test's pods
+ (`app.kubernetes.io/component: worker-auth`). Without `workers.auth` the
+ worker API has no authentication of its own, so without this rule any pod in
+ the cluster could call a remote lane directly and spend its upstream
+ credentials.
While this policy is on, `workers.networkPolicy` excludes the remote lanes, so
its `extraIngress` sources cannot reach them. NetworkPolicies are additive:
any other policy that selects these pods and admits more sources widens
@@ -1391,6 +1396,12 @@ write access, or of the read token, which every worker sidecar holds.
cannot write.
- **Gateway admin token (when set):** every gateway pod and the tooling that
manages pools.
+- **Gateway client token (when set or generated):** API clients, every gateway
+ pod, and every worker sidecar, which presents it when it calls the gateway.
+ See [Securing the cluster](#securing-the-cluster).
+- **Worker token (when `workers.auth.enabled`):** every gateway pod and every
+ worker container that serves the worker API, which is the container that
+ runs model code. All workers share it.
- **Upstream credentials (when remote backends are used):** the `worker`
container of each `remote` lane, from the Secrets that `upstreams` names.
Where each credential is sent is in the `<fullname>-upstreams` Secret, which
@@ -1512,6 +1523,260 @@ contain the generated tokens.
> to it and log a deprecation warning. Move them to `SIE_CONFIG_SERVICE_TOKEN`
> with a read token.
+## Securing the cluster
+
+By default the gateway and the workers accept requests without a token, and
+no NetworkPolicy limits who reaches the workers. The settings below close
+that, and each can be turned on now. 0.13.0 changes their defaults:
+
+| Setting | Default now | Default from 0.13.0 |
+| --- | --- | --- |
+| `gateway.auth.mode` | `none` | `token` |
+| `gateway.auth.generateToken` | `false` | `true` |
+| `workers.auth.enabled` | `false` | `true` |
+| `workers.networkPolicy.enabled` | `false` | `true` |
+| `telemetry.enabled` | `true` | `false` |
+
+To keep the current behavior after 0.13.0, set the "Default now" values
+explicitly. To adopt the 0.13.0 defaults now, which together are the secure
+combination, set:
+
+```yaml
+gateway:
+ auth:
+ mode: token
+ generateToken: true
+workers:
+ auth:
+ enabled: true
+ networkPolicy:
+ enabled: true
+telemetry:
+ enabled: false
+```
+
+An Ingress or a `LoadBalancer`/`NodePort` gateway Service also needs TLS; see
+[Authentication and TLS requirements](#authentication-and-tls-requirements).
+
+### Gateway token
+
+With `gateway.auth.mode` set to `token` (or `static`, which the gateway treats
+the same), the gateway requires a token on every request except its probes and
+API description. Clients send it as `Authorization: Bearer <token>` or
+`x-api-key: <token>`. When a request sends both, the gateway uses
+`Authorization` and ignores `x-api-key`; until 0.13.0, a repeated
+`Authorization` header uses its first value. SDK clients pass the token as
+`api_key`/`apiKey`, or read it from `SIE_API_KEY` when their base URL comes
+from `SIE_BASE_URL`. The tokens come from one Secret, generated or managed by
+the operator:
+
+- **Generated.** With `gateway.auth.tokenSecretName` empty and
+ `gateway.auth.generateToken=true`, the chart creates the Secret
+ `<fullname>-gateway-token` holding a random 64-character token under
+ `gateway.auth.tokenSecretKey` (`SIE_AUTH_TOKEN`). Like the
+ [sie-config tokens](#sie-config-tokens), upgrades read the existing Secret
+ and keep its token, the render fails if the token is missing or shorter than
+ 32 characters, the Secret carries `helm.sh/resource-policy: keep`, and
+ renderers without cluster access generate a new token on every render (see
+ [GitOps and `helm template`](#gitops-and-helm-template); use
+ `gateway.auth.tokenSecretName` there). The install notes print the command
+ that reads it:
+
+ ```bash
+ FULLNAME=sie-cluster
+ kubectl get secret -n sie "${FULLNAME}-gateway-token" \
+ -o jsonpath='{.data.SIE_AUTH_TOKEN}' | base64 -d
+ ```
+
+- **Operator-managed.** Set `gateway.auth.tokenSecretName` to a Secret holding
+ comma-separated tokens. The chart uses it unchanged and ignores
+ `gateway.auth.generateToken`. Several tokens let you rotate one at a time.
+
+While the gateway receives the generated token, `gateway.extraEnv` cannot set
+`SIE_AUTH_TOKEN` or `SIE_AUTH_TOKENS`, which would replace it.
+
+The worker sidecars receive the same Secret as `SIE_GATEWAY_API_KEY` and
+present its first comma-separated token when they call the gateway, so
+`workers.common.workerSidecar.extraEnv` cannot set `SIE_GATEWAY_API_KEY`
+while the chart wires it. The MCP edge does not receive the Secret: set
+`mcpEdge.clusterApiKey.existingSecretName` and `mcpEdge.clusterApiKey.secretKey`
+to a Secret key holding one gateway token. The MCP edge presents the whole
+value, so that key must hold a single token. The render fails when the gateway
+requires a token, `mcpEdge.enabled` is set, `mcpEdge.clusterBaseUrl` is empty
+(the edge calls the in-cluster gateway), and no cluster API key is set. With
+token auth, pool create, renew, and delete also need the
+[gateway admin token](#gateway-admin-token). The render fails when the client
+token, a `gateway.extraEnv` token Secret, or the MCP edge cluster API key is
+the same Secret key as a checked credential: the Hugging Face
+token, a NATS password, the gateway admin token, either sie-config token, an
+image pull secret, an oauth2-proxy secret, the Better Stack token, a bundled
+Grafana admin username or password in the same namespace, the MCP connector
+secrets, or a chart-managed ingress TLS key. Gateway client credentials may
+share a key with each other. The guard checks this finite list; other optional
+dependency credentials and arbitrary subchart env/volume configuration need
+operator separation. Remaining dependency cases are tracked in
+[#767](https://github.com/superlinked/sie/issues/767).
+
+When `gateway.extraEnv` sets `SIE_AUTH_MODE` from `valueFrom`, the mode is
+unknown at render time. The gateway then receives the generated token, as it
+receives an operator-managed Secret, so a mode that resolves to `none` at run
+time is refused as a misconfiguration.
+
+To turn the generated token on for an existing release without locking out
+clients, upgrade twice. Pass your values as on every upgrade. First create the
+token; the gateway does not require it yet:
+
+```bash
+helm upgrade sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \
+ --namespace sie -f values.yaml \
+ --set gateway.auth.generateToken=true
+```
+
+This step rolls the worker StatefulSets, whose sidecars receive the token.
+Give the token to your clients, then require it:
+
+```bash
+helm upgrade sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \
+ --namespace sie -f values.yaml \
+ --set gateway.auth.generateToken=true \
+ --set gateway.auth.mode=token
+```
+
+The second step rolls only the gateway.
+
+**Rotating the gateway token.** Pods read the token at start, and deleting
+the generated Secret replaces every client's token at once. For a rotation
+without a cutover, use an operator-managed Secret:
+
+1. Put the new token first and keep the old one: `new-token,old-token`. Run
+ `helm upgrade` (with the Secret's name in `gateway.auth.tokenSecretName`)
+ and restart the gateway and the worker StatefulSets. The gateway accepts
+ both tokens, and the worker sidecars present the first one.
+2. Move every client, including the MCP edge's key, to the new token.
+3. Remove the old token from the Secret and restart the gateway.
+
+To leave a generated token, copy it into your own Secret as the old token in
+step 1, then set `gateway.auth.tokenSecretName`.
+
+### Worker token
+
+The workers serve an HTTP API that the gateway calls. With
+`workers.auth.enabled=true`, every worker container that serves it receives
+`SIE_AUTH_MODE=token` and `SIE_AUTH_TOKEN` and requires the token on every
+route except `/healthz`, `/livez`, and `/readyz`, which the kubelet probes
+call without credentials. The gateway receives the same token as
+`SIE_WORKER_AUTH_TOKEN` and presents it (the first one, when the Secret key
+lists several comma-separated tokens) when it opens a worker's `/ws/status`
+connection, which it does with `gateway.healthMode=ws` or when it falls back to
+WebSocket health because NATS is unavailable at start. With the default NATS
+health mode the gateway reaches the workers only through NATS. The Rust worker
+(`engine: candle`) serves only probes over HTTP and receives no token, and the
+worker sidecars do not serve the worker API.
+
+Worker auth needs `sie-server` and `sie-gateway` images from this chart's
+release (its `appVersion`) or later. Images of 0.10.1 and earlier ignore these
+variables, so their workers serve without a token. A post-install and
+post-upgrade hook Job, `<fullname>-worker-auth-test-<revision>`, checks this
+while the workers require the token: once a worker of each lane's current
+StatefulSet revision is ready, it sends `GET /v1/models` without a token and
+fails the release when a worker answers with anything but `401`, when a ready
+worker does not answer, when a lane's StatefulSet is missing, or when its pods
+cannot be listed. Both worker NetworkPolicies admit the hook pod to the worker
+ports while the workers require the token. A lane scaled to zero is skipped at
+once, and a lane with no ready worker of the current revision within three
+minutes (a cold start longer than that) is skipped with a warning. The check is
+best effort: a skipped lane is not checked until a later release finds it
+running. The Job stays for a day after it finishes, so its log
+(`kubectl logs -n <namespace> job/<fullname>-worker-auth-test-<revision>`)
+shows which workers it checked and which lanes it skipped. Keep the image tags
+at the chart default, or override `workers.common.image.tag` only with a tag of
+the same release or later: with `workers.auth.enabled`, the render fails when
+that tag is a version older than the chart's `appVersion`.
+
+With `workers.auth.tokenSecretName` empty, the chart creates
+`<fullname>-worker-token` holding a random 64-character token under
+`workers.auth.tokenSecretKey` (`SIE_AUTH_TOKEN`), with the same reuse check,
+keep policy, and `helm template` caveat as the gateway token. Otherwise it uses
+the named Secret unchanged. The render fails when the worker token is the same
+Secret key as another checked credential listed above, including the gateway
+client token (see [Gateway token](#gateway-token) for the list). While
+`workers.auth.enabled` is set, the worker `extraEnv` lists cannot set
+`SIE_AUTH_MODE`, `SIE_AUTH_TOKEN`, or `SIE_AUTH_TOKENS`, and `gateway.extraEnv`
+cannot set `SIE_WORKER_AUTH_TOKEN`. When the workers do not require the token,
+the chart sets `SIE_AUTH_MODE=none` on the containers that serve the worker
+API. That covers the first upgrade step below (`workers.auth.enabled=true`
+with `workers.auth.allowUnauthenticated=true`), where the three variables stay
+reserved, and worker auth off, where a worker `extraEnv` list that sets one of
+them is left in charge instead. A worker therefore never generates a token of
+its own.
+
+All workers share one token, so a worker container can call the other
+workers' APIs. Keep `workers.networkPolicy` on with it, so that only the
+gateway reaches the worker ports.
+
+**Upgrading an existing release.** A single upgrade with
+`--set workers.auth.enabled=true` rolls the gateway and the workers together.
+With the default NATS health mode that is enough. With WebSocket health, a
+gateway pod that has not been replaced yet has no token, and the workers that
+restarted before it refuse its connections until it is replaced. To avoid that
+gap, upgrade in two steps. First let the gateway present the token while the
+workers do not require it yet:
+
+```bash
+helm upgrade sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \
+ --namespace sie -f values.yaml \
+ --set workers.auth.enabled=true \
+ --set workers.auth.allowUnauthenticated=true
+```
+
+This step rolls only the gateway. Once every gateway pod has restarted,
+require the token:
+
+```bash
+helm upgrade sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \
+ --namespace sie -f values.yaml \
+ --set workers.auth.enabled=true \
+ --set workers.auth.allowUnauthenticated=false
+```
+
+Set it explicitly: `--reuse-values` and `--reset-then-reuse-values` both keep
+the value from the first step. The second step rolls the workers. `helm status`
+prints a warning while `workers.auth.allowUnauthenticated` is on, and the
+render fails when it is set without `workers.auth.enabled`.
+
+**Rotating the worker token.** The gateway presents one worker token at a
+time:
+
+- With the default NATS health mode, nothing calls the worker API except the
+ probes. Delete the generated Secret (or change your own), run `helm upgrade`,
+ and restart the gateway and the worker StatefulSets.
+- With WebSocket health, use the upgrade aid: upgrade with
+ `workers.auth.allowUnauthenticated=true` and wait for the workers to restart,
+ replace the token, run `helm upgrade` and restart the gateway, then upgrade
+ with `workers.auth.allowUnauthenticated=false`. Keep `workers.networkPolicy`
+ on, since the workers accept unauthenticated requests between the first and
+ last step.
+- With your own Secret in `workers.auth.tokenSecretName`, rotate without a
+ gap: set the key to `old-token,new-token` and restart the worker
+ StatefulSets, so the workers accept both; set it to `new-token,old-token` and
+ restart the gateway, which presents the first; then set it to `new-token` and
+ restart the worker StatefulSets.
+
+### NetworkPolicy
+
+`workers.networkPolicy.enabled=true` admits this release's gateway pods to the
+worker HTTP ports (see [Worker NetworkPolicy](#worker-networkpolicy)). While
+the workers require the token, it also admits pods labelled
+`{app.kubernetes.io/name: sie-health-test, app.kubernetes.io/component: worker-auth, app.kubernetes.io/instance: <release>}`,
+the label of the release-time worker token test; any pod created with that
+label in the namespace is admitted, as for the gateway's labels. A
+NetworkPolicy takes effect only with a CNI that enforces it. Without one the
+policy admits every pod, and the worker token remains the only control. The
+kubelet probes, which the policy does not restrict, use the probe paths that
+need no token. Remote lanes have their own policy,
+`workers.remote.networkPolicy`, which admits the same pods (see
+[Network policy for remote lanes](#network-policy-for-remote-lanes)).
+
## Ingress
The Ingress is off by default, including in the AWS, GKE, AKS, and ACK
@@ -1556,9 +1821,11 @@ 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`;
+ `gateway.auth.tokenSecretName` naming a Secret of comma-separated tokens, or
+ with `gateway.auth.generateToken=true` (see
+ [Securing the cluster](#securing-the-cluster)). 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`)
@@ -1593,11 +1860,14 @@ you to create it, and `self-signed` mode does not issue it, so the chart refuses
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`.
+reads it, and token auth without `gateway.auth.tokenSecretName`,
+`gateway.auth.generateToken=true`, 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 generated token with auth mode `none` does not, because the
+gateway does not receive it until the mode is `token` or `static`. 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
@@ -1647,10 +1917,13 @@ Tune them with `SIE_GATEWAY_POOL_MAX_MINIMUM_WORKER_COUNT`,
### 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
+Worker pods serve an HTTP API that requires no token unless
+`workers.auth.enabled` is set (see [Worker token](#worker-token)); the gateway
+is the only in-chart caller of the worker API, apart from the release-time
+worker token test. `workers.networkPolicy.enabled=true` renders an ingress
+`NetworkPolicy` whose default rule admits this release's gateway pods to every
+worker HTTP port and, while the workers require the token, the worker token
+test's pods (`app.kubernetes.io/component: worker-auth`). 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
diff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txt
index fbeb84230..6a344d881 100644
--- a/deploy/helm/sie-cluster/templates/NOTES.txt
+++ b/deploy/helm/sie-cluster/templates/NOTES.txt
@@ -34,6 +34,25 @@ sie-config admin token: kubectl get secret -n {{ include "sie-cluster.namespace"
{{- if and .Values.config.enabled (include "sie-cluster.config.generatesReadToken" .) }}
sie-config read token (reads only): kubectl get secret -n {{ include "sie-cluster.namespace" . }} {{ include "sie-cluster.config.generatedReadTokenSecretName" . }} -o jsonpath='{.data.{{ include "sie-cluster.config.readTokenSecretKey" . | replace "." "\\." }}}' | base64 -d
{{- end }}
+{{- if include "sie-cluster.gateway.generatesToken" . }}
+Gateway token: kubectl get secret -n {{ include "sie-cluster.namespace" . }} {{ include "sie-cluster.gateway.generatedTokenSecretName" . }} -o jsonpath='{.data.{{ include "sie-cluster.gateway.tokenSecretKey" . | replace "." "\\." }}}' | base64 -d
+{{- $gatewayAuth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson }}
+{{- if not $gatewayAuth.known }}
+The gateway auth mode comes from gateway.extraEnv and is known only at run time. The gateway receives
+this token and requires it when that mode is token or static.
+{{- else if not (include "sie-cluster.gateway.authenticates" .) }}
+The gateway does not require this token yet (gateway auth mode none). Give it to your clients, then
+run helm upgrade again with --set gateway.auth.mode=token.
+{{- end }}
+{{- end }}
+{{- if and (include "sie-cluster.workers.authEnabled" .) (not (include "sie-cluster.workers.authEnforced" .)) }}
+
+WARNING: workers.auth.allowUnauthenticated=true. The gateway presents the worker token, but the
+workers do not require it yet: any pod that can reach a worker can call its API. This setting is
+only for the first step of the upgrade. Once every gateway pod has restarted, run helm upgrade again
+with --set workers.auth.allowUnauthenticated=false. --reuse-values and --reset-then-reuse-values
+keep it on.
+{{- end }}
{{- if $kubePrometheusStack.install }}
Prometheus: enabled - kubectl port-forward -n {{ include "sie-cluster.kubePrometheusStack.namespace" . }} svc/{{ include "sie-cluster.kubePrometheusStack.prometheusServiceName" . }} 9090:{{ include "sie-cluster.kubePrometheusStack.prometheusServicePort" . }}
{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tpl
index 25759250c..03d1932ac 100644
--- a/deploy/helm/sie-cluster/templates/_helpers.tpl
+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl
@@ -433,11 +433,143 @@ empty-value failure as the sie-config keys.
{{- $key -}}
{{- end }}
+{{/*
+Data key of the gateway client-token Secret (gateway.auth.tokenSecretKey), with
+the same absent-key default and empty-value failure as the other token keys.
+*/}}
+{{- define "sie-cluster.gateway.tokenSecretKey" -}}
+{{- $key := dig "tokenSecretKey" "SIE_AUTH_TOKEN" (.Values.gateway.auth | default dict) | default "" | toString | trim -}}
+{{- if not $key -}}
+{{- fail "gateway.auth.tokenSecretKey is empty. Set it to the Secret key that holds the gateway client tokens (the chart default is SIE_AUTH_TOKEN)." -}}
+{{- end -}}
+{{- $key -}}
+{{- end }}
+
+{{- define "sie-cluster.gateway.generatedTokenSecretName" -}}
+{{- printf "%s-token" (include "sie-cluster.gateway.serviceName" .) -}}
+{{- end }}
+
+{{/*
+"true" when the chart generates the gateway client-token Secret:
+gateway.auth.generateToken is true and gateway.auth.tokenSecretName is empty.
+*/}}
+{{- define "sie-cluster.gateway.generatesToken" -}}
+{{- $auth := .Values.gateway.auth | default dict -}}
+{{- $generate := include "sie-cluster.optIn" (dict "value" (dig "generateToken" nil $auth) "path" "gateway.auth.generateToken") -}}
+{{- if and $generate (not (dig "tokenSecretName" "" $auth)) -}}
+true
+{{- end -}}
+{{- end }}
+
+{{/*
+Secret holding the gateway client tokens, which worker sidecars present to the
+gateway: gateway.auth.tokenSecretName when set, otherwise the chart-generated
+Secret, otherwise empty.
+*/}}
+{{- define "sie-cluster.gateway.tokenSecretName" -}}
+{{- $name := dig "tokenSecretName" "" (.Values.gateway.auth | default dict) -}}
+{{- if $name -}}
+{{- $name -}}
+{{- else if include "sie-cluster.gateway.generatesToken" . -}}
+{{- include "sie-cluster.gateway.generatedTokenSecretName" . -}}
+{{- end -}}
+{{- end }}
+
+{{/*
+Secret the gateway receives as SIE_AUTH_TOKEN: gateway.auth.tokenSecretName, or
+the chart-generated Secret unless the gateway mode is known to be none. With
+auth mode none the generated Secret is not wired, so clients can read the
+token before the gateway requires it. A mode set by a gateway.extraEnv
+valueFrom is unknown at render time and gets the token, as an operator Secret
+does.
+*/}}
+{{- define "sie-cluster.gateway.enforcedTokenSecretName" -}}
+{{- $name := dig "tokenSecretName" "" (.Values.gateway.auth | default dict) -}}
+{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}
+{{- if $name -}}
+{{- $name -}}
+{{- else if and (include "sie-cluster.gateway.generatesToken" .) (or (not $auth.known) (include "sie-cluster.gateway.authenticates" .)) -}}
+{{- include "sie-cluster.gateway.generatedTokenSecretName" . -}}
+{{- end -}}
+{{- end }}
+
+{{/*
+"true" when workers.auth.enabled is true: the gateway presents the worker
+token, and the workers require it unless workers.auth.allowUnauthenticated.
+*/}}
+{{- define "sie-cluster.workers.authEnabled" -}}
+{{- include "sie-cluster.optIn" (dict "value" (dig "auth" "enabled" nil (.Values.workers | default dict)) "path" "workers.auth.enabled") -}}
+{{- end }}
+
+{{/*
+Labels of the worker-auth release test pod, which the worker NetworkPolicies
+admit to the worker ports while the workers require the token.
+*/}}
+{{- define "sie-cluster.workers.authTestSelectorLabels" -}}
+app.kubernetes.io/name: sie-health-test
+app.kubernetes.io/component: worker-auth
+app.kubernetes.io/instance: {{ .Release.Name }}
+{{- end }}
+
+{{/*
+"true" when the workers require the worker token: workers.auth.enabled and
+not workers.auth.allowUnauthenticated.
+*/}}
+{{- define "sie-cluster.workers.authEnforced" -}}
+{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" (dig "auth" "allowUnauthenticated" nil (.Values.workers | default dict)) "path" "workers.auth.allowUnauthenticated") -}}
+{{- if and (include "sie-cluster.workers.authEnabled" .) (not $allowUnauthenticated) -}}
+true
+{{- end -}}
+{{- end }}
+
+{{/*
+Data key of the worker-token Secret (workers.auth.tokenSecretKey), with the
+same absent-key default and empty-value failure as the other token keys.
+*/}}
+{{- define "sie-cluster.workers.authTokenSecretKey" -}}
+{{- $key := dig "auth" "tokenSecretKey" "SIE_AUTH_TOKEN" (.Values.workers | default dict) | default "" | toString | trim -}}
+{{- if not $key -}}
+{{- fail "workers.auth.tokenSecretKey is empty. Set it to the Secret key that holds the worker token (the chart default is SIE_AUTH_TOKEN)." -}}
+{{- end -}}
+{{- $key -}}
+{{- end }}
+
+{{- define "sie-cluster.workers.generatedAuthTokenSecretName" -}}
+{{- printf "%s-token" (include "sie-cluster.worker.serviceName" .) -}}
+{{- end }}
+
+{{/*
+"true" when the chart generates the worker-token Secret: workers.auth.enabled
+and workers.auth.tokenSecretName is empty.
+*/}}
+{{- define "sie-cluster.workers.generatesAuthToken" -}}
+{{- if and (include "sie-cluster.workers.authEnabled" .) (not (dig "auth" "tokenSecretName" "" (.Values.workers | default dict))) -}}
+true
+{{- end -}}
+{{- end }}
+
+{{/*
+Secret holding the worker token while workers.auth.enabled:
+workers.auth.tokenSecretName when set, otherwise the chart-generated Secret.
+Empty when worker auth is off.
+*/}}
+{{- define "sie-cluster.workers.authTokenSecretName" -}}
+{{- if include "sie-cluster.workers.authEnabled" . -}}
+{{- $name := dig "auth" "tokenSecretName" "" (.Values.workers | default dict) -}}
+{{- if $name -}}
+{{- $name -}}
+{{- else -}}
+{{- include "sie-cluster.workers.generatedAuthTokenSecretName" . -}}
+{{- end -}}
+{{- end -}}
+{{- end }}
+
{{/*
Chart-generated token Secret: a random 64-character token on first install,
and the existing token on upgrade (read with lookup and validated rather than
replaced). Kept on uninstall. Args (dict): root, name (Secret), key (data key),
-keySetting and nameSetting (the values paths named in validation errors).
+keySetting and nameSetting (the values paths named in validation errors), and
+optionally labels (the labels template, default sie-cluster.config.labels).
*/}}
{{- define "sie-cluster.config.generatedTokenSecret" -}}
{{- $token := randAlphaNum 64 | b64enc -}}
@@ -452,7 +584,7 @@ metadata:
name: {{ .name }}
namespace: {{ include "sie-cluster.namespace" .root }}
labels:
- {{- include "sie-cluster.config.labels" .root | nindent 4 }}
+ {{- include (default "sie-cluster.config.labels" .labels) .root | nindent 4 }}
annotations:
helm.sh/resource-policy: keep
type: Opaque
@@ -877,14 +1009,14 @@ and token, and refuses every request when token auth has no 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 -}}
+{{- $tokenSource := include "sie-cluster.gateway.tokenSecretName" . -}}
{{- 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) -}}
+{{- fail (printf "gateway auth mode %q needs tokens: set gateway.auth.tokenSecretName to a Secret holding comma-separated tokens, or set gateway.auth.generateToken=true so the chart generates one, 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." -}}
@@ -892,6 +1024,174 @@ and token, and refuses every request when token auth has no token.
{{- end -}}
{{- end }}
+{{/*
+Validation: the MCP edge calls the in-cluster gateway unless
+mcpEdge.clusterBaseUrl points elsewhere. When that gateway enforces token auth,
+or its auth mode is known only at run time, the edge needs a client token, or
+every tool call may be refused.
+*/}}
+{{- define "sie-cluster.mcpEdge.validateGatewayToken" -}}
+{{- $mcp := .Values.mcpEdge | default dict -}}
+{{- $auth := include "sie-cluster.gateway.effectiveAuthMode" . | fromJson -}}
+{{- $mayAuthenticate := or (include "sie-cluster.gateway.authenticates" .) (not $auth.known) -}}
+{{- if and $mcp.enabled (not $mcp.clusterBaseUrl) (not (dig "clusterApiKey" "existingSecretName" "" $mcp)) $mayAuthenticate -}}
+{{- $example := "" -}}
+{{- with include "sie-cluster.gateway.tokenSecretName" . -}}
+{{- $example = printf ", for example mcpEdge.clusterApiKey.existingSecretName=%s and mcpEdge.clusterApiKey.secretKey=%s" . (include "sie-cluster.gateway.tokenSecretKey" $) -}}
+{{- end -}}
+{{- fail (printf "mcpEdge.enabled with gateway token auth (or a gateway auth mode known only at run time) needs mcpEdge.clusterApiKey.existingSecretName: the MCP edge calls the in-cluster gateway, which refuses requests without a token. Point it at a Secret key that holds one gateway client token%s." $example) -}}
+{{- end -}}
+{{- end }}
+
+{{/*
+Validation: workers.auth.allowUnauthenticated is the first step of the
+two-step upgrade and needs workers.auth.enabled.
+*/}}
+{{- define "sie-cluster.workers.validateAuth" -}}
+{{- $allowUnauthenticated := include "sie-cluster.optIn" (dict "value" (dig "auth" "allowUnauthenticated" nil (.Values.workers | default dict)) "path" "workers.auth.allowUnauthenticated") -}}
+{{- if and $allowUnauthenticated (not (include "sie-cluster.workers.authEnabled" .)) -}}
+{{- fail "workers.auth.allowUnauthenticated=true needs workers.auth.enabled=true: it is the first step of the two-step upgrade, in which the gateway presents the worker token and the workers do not require it yet. Set workers.auth.enabled=true with it, or remove it." -}}
+{{- end -}}
+{{- $tag := toString (dig "common" "image" "tag" "" (.Values.workers | default dict)) -}}
+{{- if and (include "sie-cluster.workers.authEnabled" .) .Chart.AppVersion (regexMatch "^v?[0-9]+\\.[0-9]+\\.[0-9]+$" $tag) (semverCompare (printf "<%s" .Chart.AppVersion) $tag) -}}
+{{- fail (printf "workers.auth.enabled needs sie-server images from this chart's release (%s) or later, which enforce the worker token; workers.common.image.tag=%s is older, so its workers would serve without a token. Remove the tag override or set a tag of this release or later." .Chart.AppVersion $tag) -}}
+{{- end -}}
+{{- end }}
+
+{{/*
+Validation: the worker token and every gateway client credential (the gateway
+client token, gateway.extraEnv token Secrets, and the MCP edge cluster API
+key) are kept apart from the other known credential keys listed in
+sie-cluster.wiredSecretKeys. A client or worker token that is also another
+credential's Secret key hands that credential to every holder of the token:
+API clients, worker sidecars, the MCP edge, or the worker containers that run
+model code. Gateway client credentials may share a key with each other.
+*/}}
+{{- define "sie-cluster.validateTokenSeparation" -}}
+{{- $keys := include "sie-cluster.wiredSecretKeys" . | fromJsonArray -}}
+{{- range $token := $keys -}}
+{{- if eq (default "" $token.role) "worker" -}}
+{{- range $other := $keys -}}
+{{- if and (ne (default "" $other.role) "worker") (eq $other.ref $token.ref) -}}
+{{- fail (printf "The worker token and the %s are the same Secret key (%s), so every holder of one would hold the other, including the worker containers that run model code. Store them in different Secrets or keys." $other.name $token.ref) -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- range $token := $keys -}}
+{{- if eq (default "" $token.role) "gateway-client" -}}
+{{- range $other := $keys -}}
+{{- if and (eq (default "" $other.role) "") (eq $other.ref $token.ref) -}}
+{{- fail (printf "The %s and the %s are the same Secret key (%s), so every holder of the %s would also hold the %s. Store them in different Secrets or keys." $token.name $other.name $token.ref $token.name $other.name) -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- end }}
+
+{{/*
+Known chart credential keys, as a JSON list of
+{owner, name, ref, role}: owner is the values path or a description used in
+upstream errors, name is a label for separation errors, ref is "secret/key",
+and role is "gateway-client" for credentials presented to the gateway as a
+client token, "worker" for the worker token, and empty otherwise. Both the
+token-separation check and the upstream-key collision check read this list.
+*/}}
+{{- define "sie-cluster.wiredSecretKeys" -}}
+{{- $root := . -}}
+{{- $keys := list -}}
+{{- $hfCache := $root.Values.workers.common.hfCache | default dict -}}
+{{- with $hfCache.tokenSecret -}}
+{{- $keys = append $keys (dict "owner" "workers.common.hfCache.tokenSecret" "name" "Hugging Face token" "ref" (printf "%s/%s" . $hfCache.tokenSecretKey)) -}}
+{{- end -}}
+{{- $gatewayAuth := $root.Values.gateway.auth | default dict -}}
+{{- with include "sie-cluster.gateway.tokenSecretName" $root -}}
+{{- $keys = append $keys (dict "owner" (ternary "gateway.auth.tokenSecretName" "the generated gateway client token" (ne (dig "tokenSecretName" "" $gatewayAuth) "")) "name" "gateway client token" "ref" (printf "%s/%s" . (include "sie-cluster.gateway.tokenSecretKey" $root)) "role" "gateway-client") -}}
+{{- end -}}
+{{- range $entry := (default (list) $root.Values.gateway.extraEnv) -}}
+{{- if and (kindIs "map" $entry) (has (toString (index $entry "name")) (list "SIE_AUTH_TOKEN" "SIE_AUTH_TOKENS")) -}}
+{{- $secretRef := dig "valueFrom" "secretKeyRef" dict $entry -}}
+{{- if and $secretRef.name $secretRef.key -}}
+{{- $keys = append $keys (dict "owner" (printf "gateway.extraEnv %s" (index $entry "name")) "name" (printf "gateway client token from gateway.extraEnv %s" (index $entry "name")) "ref" (printf "%s/%s" $secretRef.name $secretRef.key) "role" "gateway-client") -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- with include "sie-cluster.workers.authTokenSecretName" $root -}}
+{{- $keys = append $keys (dict "owner" (ternary "workers.auth.tokenSecretName" "the generated worker token" (ne (dig "auth" "tokenSecretName" "" $root.Values.workers) "")) "name" "worker token" "ref" (printf "%s/%s" . (include "sie-cluster.workers.authTokenSecretKey" $root)) "role" "worker") -}}
+{{- end -}}
+{{- with $gatewayAuth.adminTokenSecretName -}}
+{{- $keys = append $keys (dict "owner" "gateway.auth.adminTokenSecretName" "name" "gateway admin token" "ref" (printf "%s/%s" . (include "sie-cluster.gateway.adminTokenSecretKey" $root))) -}}
+{{- end -}}
+{{- with include "sie-cluster.config.readTokenSecretName" $root -}}
+{{- $keys = append $keys (dict "owner" "the sie-config read token" "name" "sie-config read token" "ref" (printf "%s/%s" . (include "sie-cluster.config.readTokenSecretKey" $root))) -}}
+{{- end -}}
+{{- with include "sie-cluster.config.adminTokenSecretName" $root -}}
+{{- $keys = append $keys (dict "owner" "the sie-config admin token" "name" "sie-config admin token" "ref" (printf "%s/%s" . (include "sie-cluster.config.adminTokenSecretKey" $root))) -}}
+{{- end -}}
+{{- range $secretName := $root.Values.global.imagePullSecrets -}}
+{{- range $key := list ".dockerconfigjson" ".dockercfg" -}}
+{{- $keys = append $keys (dict "owner" "global.imagePullSecrets" "name" "image pull secret" "ref" (printf "%s/%s" $secretName $key)) -}}
+{{- end -}}
+{{- end -}}
+{{- $oauthSecret := $root.Values.auth.oauth2Proxy.secret -}}
+{{- with $oauthSecret.name -}}
+{{- $secretName := . -}}
+{{- range $keyField := list "clientIDKey" "clientSecretKey" "cookieSecretKey" -}}
+{{- $keys = append $keys (dict "owner" (printf "auth.oauth2Proxy.secret.%s" $keyField) "name" (printf "oauth2-proxy %s" $keyField) "ref" (printf "%s/%s" $secretName (index $oauthSecret $keyField))) -}}
+{{- end -}}
+{{- end -}}
+{{- $betterStack := $root.Values.observability.otel.collector.betterStack -}}
+{{- with $betterStack.existingSecret -}}
+{{- $keys = append $keys (dict "owner" "observability.otel.collector.betterStack.existingSecret" "name" "Better Stack token" "ref" (printf "%s/%s" . $betterStack.tokenKey)) -}}
+{{- end -}}
+{{- with index $root.Subcharts "kube-prometheus-stack" -}}
+{{- with index .Subcharts "grafana" -}}
+{{- if eq (include "grafana.namespace" .) (include "sie-cluster.namespace" $root) -}}
+{{- $context := merge (dict "Template" $root.Template) . -}}
+{{- $secretName := tpl .Values.admin.existingSecret $context | default (include "grafana.fullname" .) -}}
+{{- if and (not .Values.env.GF_SECURITY_ADMIN_USER) (not .Values.env.GF_SECURITY_DISABLE_INITIAL_ADMIN_CREATION) -}}
+{{- $keys = append $keys (dict "owner" "the Grafana admin username" "name" "Grafana admin username" "ref" (printf "%s/%s" $secretName (default "admin-user" .Values.admin.userKey))) -}}
+{{- end -}}
+{{- if and (not .Values.env.GF_SECURITY_ADMIN_PASSWORD) (not .Values.env.GF_SECURITY_ADMIN_PASSWORD__FILE) (not .Values.env.GF_SECURITY_DISABLE_INITIAL_ADMIN_CREATION) -}}
+{{- $keys = append $keys (dict "owner" "the Grafana admin password" "name" "Grafana admin password" "ref" (printf "%s/%s" $secretName (default "admin-password" .Values.admin.passwordKey))) -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- $mcp := $root.Values.mcpEdge -}}
+{{- if or $mcp.connectorSecrets $mcp.existingSecretName -}}
+{{- $keys = append $keys (dict "owner" "the MCP connector secrets" "name" "MCP connector secrets" "ref" (printf "%s/connector-secrets" (include "sie-cluster.mcpEdge.secretName" $root))) -}}
+{{- end -}}
+{{- with $mcp.clusterApiKey.existingSecretName -}}
+{{- $keys = append $keys (dict "owner" "mcpEdge.clusterApiKey.existingSecretName" "name" "MCP edge cluster API key" "ref" (printf "%s/%s" . $mcp.clusterApiKey.secretKey) "role" "gateway-client") -}}
+{{- end -}}
+{{- $tls := include "sie-cluster.ingressTlsConfig" $root | fromYaml -}}
+{{- $tlsSecrets := list (dict "owner" "the ingress TLS certificate" "name" $tls.secretName) (dict "owner" "the MCP ingress TLS certificate" "name" (printf "%s-tls" (include "sie-cluster.mcpEdge.serviceName" $root))) -}}
+{{- $rootCA := dig "selfSigned" "rootCA" dict $tls -}}
+{{- $namespace := include "sie-cluster.namespace" $root -}}
+{{- if eq (default $namespace $rootCA.namespace) $namespace -}}
+{{- $tlsSecrets = append $tlsSecrets (dict "owner" "the ingress root CA" "name" $rootCA.secretName) -}}
+{{- end -}}
+{{- range $tlsSecret := $tlsSecrets -}}
+{{- if $tlsSecret.name -}}
+{{- range $key := list "tls.crt" "tls.key" -}}
+{{- $keys = append $keys (dict "owner" $tlsSecret.owner "name" (trimPrefix "the " $tlsSecret.owner) "ref" (printf "%s/%s" $tlsSecret.name $key)) -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- if include "sie-cluster.nats.authEnabled" $root -}}
+{{- $components := include "sie-cluster.nats.authComponents" $root | fromJsonArray -}}
+{{- if dig "config" "cluster" "enabled" false $root.Values.nats -}}
+{{- $components = append $components "route" -}}
+{{- end -}}
+{{- range $component := $components -}}
+{{- $natsSecret := include "sie-cluster.nats.authSecretName" (dict "auth" $root.Values.nats.auth "release" $root.Release.Name "component" $component) -}}
+{{- $keys = append $keys (dict "owner" (printf "the NATS %s password" $component) "name" (printf "NATS %s password" $component) "ref" (printf "%s/password" $natsSecret)) -}}
+{{- end -}}
+{{- end -}}
+{{- $keys | toJson -}}
+{{- end }}
+
{{/*
Validation: the oauth2-proxy edge (auth.enabled) is enforced only by an
ingress-nginx controller, which honours the nginx.ingress.kubernetes.io/auth-*
@@ -967,7 +1267,7 @@ ingress.allowPlaintext opt-in.
{{- $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) -}}
+{{- 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 gateway.auth.generateToken=true) 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 -}}
@@ -1010,7 +1310,7 @@ stays ClusterIP.
{{- 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) -}}
+{{- 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 gateway.auth.generateToken=true), 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 -}}
@@ -1835,71 +2135,7 @@ credential pasted as a key would otherwise be printed.
{{- if and $evidenceConfigMap (not (and (le (len $evidenceConfigMap) 253) (regexMatch "^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$" $evidenceConfigMap))) -}}
{{- fail "workers.remote.equivalence.configMap must be a valid ConfigMap name" -}}
{{- end -}}
-{{- $chartSecretKeys := list -}}
-{{- $hfCache := $root.Values.workers.common.hfCache | default dict -}}
-{{- with $hfCache.tokenSecret -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "workers.common.hfCache.tokenSecret" "ref" (printf "%s/%s" . $hfCache.tokenSecretKey)) -}}
-{{- end -}}
-{{- $gatewayAuth := $root.Values.gateway.auth | default dict -}}
-{{- with $gatewayAuth.tokenSecretName -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "gateway.auth.tokenSecretName" "ref" (printf "%s/%s" . $gatewayAuth.tokenSecretKey)) -}}
-{{- end -}}
-{{- with $gatewayAuth.adminTokenSecretName -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "gateway.auth.adminTokenSecretName" "ref" (printf "%s/%s" . (include "sie-cluster.gateway.adminTokenSecretKey" $root))) -}}
-{{- end -}}
-{{- with include "sie-cluster.config.readTokenSecretName" $root -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "the sie-config read token" "ref" (printf "%s/%s" . (include "sie-cluster.config.readTokenSecretKey" $root))) -}}
-{{- end -}}
-{{- with include "sie-cluster.config.adminTokenSecretName" $root -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "the sie-config admin token" "ref" (printf "%s/%s" . (include "sie-cluster.config.adminTokenSecretKey" $root))) -}}
-{{- end -}}
-{{- range $secretName := $root.Values.global.imagePullSecrets -}}
-{{- range $key := list ".dockerconfigjson" ".dockercfg" -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "global.imagePullSecrets" "ref" (printf "%s/%s" $secretName $key)) -}}
-{{- end -}}
-{{- end -}}
-{{- $oauthSecret := $root.Values.auth.oauth2Proxy.secret -}}
-{{- with $oauthSecret.name -}}
-{{- $secretName := . -}}
-{{- range $keyField := list "clientIDKey" "clientSecretKey" "cookieSecretKey" -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" (printf "auth.oauth2Proxy.secret.%s" $keyField) "ref" (printf "%s/%s" $secretName (index $oauthSecret $keyField))) -}}
-{{- end -}}
-{{- end -}}
-{{- $betterStack := $root.Values.observability.otel.collector.betterStack -}}
-{{- with $betterStack.existingSecret -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "observability.otel.collector.betterStack.existingSecret" "ref" (printf "%s/%s" . $betterStack.tokenKey)) -}}
-{{- end -}}
-{{- $mcp := $root.Values.mcpEdge -}}
-{{- if or $mcp.connectorSecrets $mcp.existingSecretName -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "the MCP connector secrets" "ref" (printf "%s/connector-secrets" (include "sie-cluster.mcpEdge.secretName" $root))) -}}
-{{- end -}}
-{{- with $mcp.clusterApiKey.existingSecretName -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" "mcpEdge.clusterApiKey.existingSecretName" "ref" (printf "%s/%s" . $mcp.clusterApiKey.secretKey)) -}}
-{{- end -}}
-{{- $tls := include "sie-cluster.ingressTlsConfig" $root | fromYaml -}}
-{{- $tlsSecrets := list (dict "owner" "the ingress TLS certificate" "name" $tls.secretName) (dict "owner" "the MCP ingress TLS certificate" "name" (printf "%s-tls" (include "sie-cluster.mcpEdge.serviceName" $root))) -}}
-{{- $rootCA := dig "selfSigned" "rootCA" dict $tls -}}
-{{- $namespace := include "sie-cluster.namespace" $root -}}
-{{- if eq (default $namespace $rootCA.namespace) $namespace -}}
-{{- $tlsSecrets = append $tlsSecrets (dict "owner" "the ingress root CA" "name" $rootCA.secretName) -}}
-{{- end -}}
-{{- range $tlsSecret := $tlsSecrets -}}
-{{- if $tlsSecret.name -}}
-{{- range $key := list "tls.crt" "tls.key" -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" $tlsSecret.owner "ref" (printf "%s/%s" $tlsSecret.name $key)) -}}
-{{- end -}}
-{{- end -}}
-{{- end -}}
-{{- if include "sie-cluster.nats.authEnabled" $root -}}
-{{- $components := include "sie-cluster.nats.authComponents" $root | fromJsonArray -}}
-{{- if dig "config" "cluster" "enabled" false $root.Values.nats -}}
-{{- $components = append $components "route" -}}
-{{- end -}}
-{{- range $component := $components -}}
-{{- $natsSecret := include "sie-cluster.nats.authSecretName" (dict "auth" $root.Values.nats.auth "release" $root.Release.Name "component" $component) -}}
-{{- $chartSecretKeys = append $chartSecretKeys (dict "owner" (printf "the NATS %s password" $component) "ref" (printf "%s/password" $natsSecret)) -}}
-{{- end -}}
-{{- end -}}
+{{- $chartSecretKeys := include "sie-cluster.wiredSecretKeys" $root | fromJsonArray -}}
{{- $upstreamsSecretName := include "sie-cluster.upstreams.secretName" $root -}}
{{- $upstreamsFileRef := printf "%s/upstreams.yaml" $upstreamsSecretName -}}
{{- if $upstreams -}}
diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml
index ab2588604..ad3c1582e 100644
--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml
+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml
@@ -1,4 +1,6 @@
{{- include "sie-cluster.validateGatewayAuth" . }}
+{{- include "sie-cluster.workers.validateAuth" . }}
+{{- include "sie-cluster.validateTokenSeparation" . }}
{{- /* Validate: at most one static overlay may be active. Zero overlays is the
default; the gateway fetches bundles+models from sie-config at startup
and has NO baked-in filesystem seed (see
@@ -42,6 +44,12 @@
"SIE_STREAM_MAX_AGE_S"
"SIE_STREAM_REPLICAS"
"SIE_STREAM_STORAGE") -}}
+{{- if include "sie-cluster.workers.authEnabled" . -}}
+{{- $reservedGatewayEnv = append $reservedGatewayEnv "SIE_WORKER_AUTH_TOKEN" -}}
+{{- end -}}
+{{- if and (include "sie-cluster.gateway.generatesToken" .) (include "sie-cluster.gateway.enforcedTokenSecretName" .) -}}
+{{- $reservedGatewayEnv = concat $reservedGatewayEnv (list "SIE_AUTH_TOKEN" "SIE_AUTH_TOKENS") -}}
+{{- end -}}
{{- include "sie-cluster.env.assertNoReserved" (dict "path" "gateway.extraEnv" "entries" .Values.gateway.extraEnv "reserved" $reservedGatewayEnv) -}}
{{- range $annotation := list "checksum/gpu-config" "checksum/otel-resource" -}}
{{- if hasKey $.Values.gateway.podAnnotations $annotation -}}
@@ -265,12 +273,12 @@ spec:
# Gateway auth (static token)
- name: SIE_AUTH_MODE
value: {{ .Values.gateway.auth.mode | quote }}
- {{- if .Values.gateway.auth.tokenSecretName }}
+ {{- with include "sie-cluster.gateway.enforcedTokenSecretName" . }}
- name: SIE_AUTH_TOKEN
valueFrom:
secretKeyRef:
- name: {{ .Values.gateway.auth.tokenSecretName }}
- key: {{ .Values.gateway.auth.tokenSecretKey }}
+ name: {{ . }}
+ key: {{ include "sie-cluster.gateway.tokenSecretKey" $ }}
{{- end }}
{{- with dig "adminTokenSecretName" "" (.Values.gateway.auth | default dict) }}
# Inbound admin token for POST, PUT, and DELETE under /v1/pools,
@@ -281,6 +289,13 @@ spec:
name: {{ . }}
key: {{ include "sie-cluster.gateway.adminTokenSecretKey" $ }}
{{- end }}
+ {{- with include "sie-cluster.workers.authTokenSecretName" . }}
+ - name: SIE_WORKER_AUTH_TOKEN
+ valueFrom:
+ secretKeyRef:
+ name: {{ . }}
+ key: {{ include "sie-cluster.workers.authTokenSecretKey" $ }}
+ {{- end }}
- name: SIE_THRESHOLD_ROUTING_ENABLED
value: {{ dig "thresholdRouting" "enabled" false .Values.gateway | quote }}
{{- if dig "thresholdRouting" "enabled" false .Values.gateway }}
diff --git a/deploy/helm/sie-cluster/templates/gateway-token-secret.yaml b/deploy/helm/sie-cluster/templates/gateway-token-secret.yaml
new file mode 100644
index 000000000..19a9de0f4
--- /dev/null
+++ b/deploy/helm/sie-cluster/templates/gateway-token-secret.yaml
@@ -0,0 +1,3 @@
+{{- if include "sie-cluster.gateway.generatesToken" . }}
+{{- include "sie-cluster.config.generatedTokenSecret" (dict "root" . "name" (include "sie-cluster.gateway.generatedTokenSecretName" .) "key" (include "sie-cluster.gateway.tokenSecretKey" .) "keySetting" "gateway.auth.tokenSecretKey" "nameSetting" "gateway.auth.tokenSecretName" "labels" "sie-cluster.gateway.labels") }}
+{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/hooks/worker-auth-test.yaml b/deploy/helm/sie-cluster/templates/hooks/worker-auth-test.yaml
new file mode 100644
index 000000000..85bd14d80
--- /dev/null
+++ b/deploy/helm/sie-cluster/templates/hooks/worker-auth-test.yaml
@@ -0,0 +1,181 @@
+{{- if include "sie-cluster.workers.authEnforced" . }}
+{{- $root := . -}}
+{{- $name := printf "%s-worker-auth-test" (include "sie-cluster.fullname" .) | trunc 63 | trimSuffix "-" -}}
+{{- $lanes := list -}}
+{{- range $poolName, $pool := .Values.workers.pools -}}
+{{- if $pool.enabled -}}
+{{- range $bundleName, $bundleCfg := $pool.bundles -}}
+{{- if dig "enabled" true $bundleCfg -}}
+{{- $engine := default (default $root.Values.workers.common.engine $pool.engine) $bundleCfg.engine -}}
+{{- if ne $engine "candle" -}}
+{{- $lanes = append $lanes (printf "%s-worker-%s-%s" (include "sie-cluster.fullname" $root) $poolName $bundleName) -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+{{- end -}}
+# RBAC must be at a lower weight than the Job so it is fully propagated before the pod starts.
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: {{ $name }}
+ namespace: {{ include "sie-cluster.namespace" . }}
+ labels:
+ app.kubernetes.io/name: sie-health-test
+ app.kubernetes.io/component: worker-auth
+ annotations:
+ helm.sh/hook: post-install,post-upgrade
+ helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded,hook-failed
+ helm.sh/hook-weight: "2"
+---
+apiVersion: rbac.authorization.k8s.io/v1
+kind: Role
+metadata:
+ name: {{ $name }}
+ namespace: {{ include "sie-cluster.namespace" . }}
+ labels:
+ app.kubernetes.io/name: sie-health-test
+ app.kubernetes.io/component: worker-auth
+ annotations:
+ helm.sh/hook: post-install,post-upgrade
+ helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded,hook-failed
+ helm.sh/hook-weight: "2"
+rules:
+ - apiGroups: ["apps"]
+ resources: ["statefulsets"]
+ resourceNames:
+ {{- toYaml $lanes | nindent 6 }}
+ verbs: ["get"]
+ - apiGroups: [""]
+ resources: ["pods"]
+ verbs: ["list"]
+---
+apiVersion: rbac.authorization.k8s.io/v1
+kind: RoleBinding
+metadata:
+ name: {{ $name }}
+ namespace: {{ include "sie-cluster.namespace" . }}
+ labels:
+ app.kubernetes.io/name: sie-health-test
+ app.kubernetes.io/component: worker-auth
+ annotations:
+ helm.sh/hook: post-install,post-upgrade
+ helm.sh/hook-delete-policy: before-hook-creation,hook-succeeded,hook-failed
+ helm.sh/hook-weight: "2"
+roleRef:
+ apiGroup: rbac.authorization.k8s.io
+ kind: Role
+ name: {{ $name }}
+subjects:
+ - kind: ServiceAccount
+ name: {{ $name }}
+ namespace: {{ include "sie-cluster.namespace" . }}
+---
+apiVersion: batch/v1
+kind: Job
+metadata:
+ name: {{ printf "%s-worker-auth-test-%d" (include "sie-cluster.fullname" .) .Release.Revision | trunc 63 | trimSuffix "-" }}
+ namespace: {{ include "sie-cluster.namespace" . }}
+ labels:
+ app.kubernetes.io/name: sie-health-test
+ app.kubernetes.io/component: worker-auth
+ annotations:
+ helm.sh/hook: post-install,post-upgrade
+ helm.sh/hook-delete-policy: before-hook-creation
+ helm.sh/hook-weight: "5"
+spec:
+ backoffLimit: 0
+ activeDeadlineSeconds: 300
+ ttlSecondsAfterFinished: 86400
+ template:
+ metadata:
+ labels:
+ {{- include "sie-cluster.workers.authTestSelectorLabels" . | nindent 8 }}
+ spec:
+ serviceAccountName: {{ $name }}
+ restartPolicy: Never
+ containers:
+ - name: test
+ image: {{ include "sie-cluster.keda.hookImage" . }}
+ command: ["/bin/sh", "-c"]
+ args:
+ - |
+ set -eu
+ set -o pipefail
+ NAMESPACE="{{ include "sie-cluster.namespace" . }}"
+ {{- include "sie-cluster.kubernetes.inClusterKubeconfig" . | nindent 14 }}
+ LANES="{{ join " " $lanes }}"
+ PORT={{ .Values.workers.common.port }}
+ DEADLINE=$(( $(date +%s) + 180 ))
+ echo "=== Worker token test ==="
+ echo "Every ready worker of the current revision must refuse GET /v1/models without a token."
+ verified=0
+ for lane in $LANES; do
+ if ! replicas=$(kubectl get statefulset "$lane" -o jsonpath='{.spec.replicas}'); then
+ echo "FAILED: StatefulSet $lane not found."
+ exit 1
+ fi
+ state=waiting
+ if [ "$replicas" = "0" ]; then
+ echo "SKIPPED: $lane is scaled to zero."
+ state=skipped
+ fi
+ while [ "$state" = "waiting" ]; do
+ revision=$(kubectl get statefulset "$lane" -o jsonpath='{.status.updateRevision}')
+ if ! addresses=$(kubectl get pods -l "controller-revision-hash=$revision" -o json \
+ | jq -r '.items[] | select(.metadata.deletionTimestamp == null)
+ | select(any(.status.conditions[]?; .type == "Ready" and .status == "True"))
+ | .status.podIP // empty'); then
+ echo "FAILED: cannot list the pods of $lane."
+ exit 1
+ fi
+ unreached=0
+ if [ -n "$addresses" ]; then
+ for address in $addresses; do
+ case "$address" in
+ *:*) host="[$address]" ;;
+ *) host="$address" ;;
+ esac
+ code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "http://$host:$PORT/v1/models" || true)
+ case "$code" in
+ 401)
+ echo "$lane $address: refused without a token"
+ verified=$((verified + 1)) ;;
+ 000|"")
+ echo "$lane $address: not reached"
+ unreached=$((unreached + 1)) ;;
+ *)
+ echo "FAILED: $lane $address answered GET /v1/models without a token (HTTP $code)."
+ echo "Its sie-server image does not enforce workers.auth. Use worker images from the same release as the chart."
+ exit 1 ;;
+ esac
+ done
+ if [ "$unreached" -eq 0 ]; then
+ state=checked
+ fi
+ fi
+ if [ "$state" = "waiting" ]; then
+ if [ "$(date +%s)" -lt "$DEADLINE" ]; then
+ sleep 5
+ elif [ "$unreached" -gt 0 ]; then
+ echo "FAILED: $lane has ready workers that did not answer from this pod."
+ exit 1
+ else
+ echo "WARNING: $lane has no ready worker of the current revision to check (still starting)."
+ state=skipped
+ fi
+ fi
+ done
+ done
+ if [ "$verified" -eq 0 ]; then
+ echo "WARNING: no worker was checked. Every lane was scaled to zero or still starting."
+ else
+ echo "SUCCESS: $verified worker(s) refused a request without a token."
+ fi
+ resources:
+ {{- include "sie-cluster.hooks.resources" . | nindent 12 }}
+ tolerations:
+ - key: nvidia.com/gpu
+ operator: Exists
+ effect: NoSchedule
+{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml
index f23a96db8..ce76a8502 100644
--- a/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml
+++ b/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml
@@ -1,4 +1,5 @@
{{- if .Values.mcpEdge.enabled }}
+{{- include "sie-cluster.mcpEdge.validateGatewayToken" . }}
apiVersion: apps/v1
kind: Deployment
metadata:
diff --git a/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml b/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml
index 1f41dc89c..5b3234a07 100644
--- a/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-networkpolicy.yaml
@@ -61,6 +61,11 @@ spec:
- podSelector:
matchLabels:
{{- include "sie-cluster.gateway.selectorLabels" . | nindent 14 }}
+ {{- if include "sie-cluster.workers.authEnforced" . }}
+ - podSelector:
+ matchLabels:
+ {{- include "sie-cluster.workers.authTestSelectorLabels" . | nindent 14 }}
+ {{- end }}
ports:
{{- range $i := until $maxWorkerChildCount }}
- port: {{ add $.Values.workers.common.port $i }}
diff --git a/deploy/helm/sie-cluster/templates/worker-remote-networkpolicy.yaml b/deploy/helm/sie-cluster/templates/worker-remote-networkpolicy.yaml
index 1bdc69553..4597c79f6 100644
--- a/deploy/helm/sie-cluster/templates/worker-remote-networkpolicy.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-remote-networkpolicy.yaml
@@ -90,6 +90,11 @@ spec:
- podSelector:
matchLabels:
{{- include "sie-cluster.gateway.selectorLabels" $root | nindent 14 }}
+ {{- if include "sie-cluster.workers.authEnforced" $root }}
+ - podSelector:
+ matchLabels:
+ {{- include "sie-cluster.workers.authTestSelectorLabels" $root | nindent 14 }}
+ {{- end }}
ports:
{{- range $i := until $maxWorkerChildCount }}
- port: {{ add $root.Values.workers.common.port $i }}
diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
index 81aae3082..6be727df8 100644
--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
@@ -37,6 +37,11 @@ fast at render time.
{{- range $upstreamName, $_ := (default dict $root.Values.upstreams) -}}
{{- $reservedWorkerEnv = append $reservedWorkerEnv (include "sie-cluster.upstream.keyEnvName" $upstreamName) -}}
{{- end -}}
+{{- $workerAuthEnforced := include "sie-cluster.workers.authEnforced" $root -}}
+{{- $workerAuthEnvNames := list "SIE_AUTH_MODE" "SIE_AUTH_TOKEN" "SIE_AUTH_TOKENS" -}}
+{{- if include "sie-cluster.workers.authEnabled" $root -}}
+{{- $reservedWorkerEnv = concat $reservedWorkerEnv $workerAuthEnvNames -}}
+{{- end -}}
{{- /* The SIE_STREAM_* trio is chart-owned on the sidecar for the same
reason as on the gateway: both create the work streams, first creator
wins, so the chart renders one value onto both. An extraEnv override
@@ -45,6 +50,9 @@ fast at render time.
sie-config credential comes only from config.auth, so SIE_ADMIN_TOKEN and
SIE_CONFIG_SERVICE_TOKEN are reserved too. */}}
{{- $reservedSidecarEnv := concat $reservedOtelEnv (list "SIE_ADMIN_TOKEN" "SIE_BUNDLE" "SIE_CONFIG_SERVICE_TOKEN" "SIE_GPU_COUNT" "SIE_HEALTH_PUBLISH_ENABLED" "SIE_HEALTH_PUBLISH_INTERVAL_MS" "SIE_MACHINE_PROFILE" "SIE_NATS_PASSWORD" "SIE_NATS_USER" "SIE_OTEL_LANE" "SIE_POOL" "SIE_STREAM_MAX_AGE_S" "SIE_STREAM_REPLICAS" "SIE_STREAM_STORAGE" "SIE_WORKER_ID") -}}
+{{- if include "sie-cluster.gateway.tokenSecretName" $root -}}
+{{- $reservedSidecarEnv = append $reservedSidecarEnv "SIE_GATEWAY_API_KEY" -}}
+{{- end -}}
{{- include "sie-cluster.env.assertNoReserved" (dict "path" "workers.common.extraEnv" "entries" $root.Values.workers.common.extraEnv "reserved" $reservedWorkerEnv) -}}
{{- include "sie-cluster.env.assertNoReserved" (dict "path" "workers.common.workerSidecar.extraEnv" "entries" $root.Values.workers.common.workerSidecar.extraEnv "reserved" $reservedSidecarEnv) -}}
{{- range $poolName, $pool := .Values.workers.pools }}
@@ -66,6 +74,12 @@ fast at render time.
{{- $bundle := $lane.bundle }}
{{- $workerTargetName := printf "%s-worker-%s-%s" (include "sie-cluster.fullname" $root) $poolName $bundleName -}}
{{- include "sie-cluster.env.assertNoReserved" (dict "path" (printf "workers.pools.%s.bundles.%s.extraEnv" $poolName $bundleName) "entries" $bundleCfg.extraEnv "reserved" $reservedWorkerEnv) -}}
+{{- $extraEnvSetsWorkerAuth := false -}}
+{{- range $entry := concat (default (list) $root.Values.workers.common.extraEnv) (default (list) $bundleCfg.extraEnv) -}}
+{{- if and (kindIs "map" $entry) (has (toString (index $entry "name")) $workerAuthEnvNames) -}}
+{{- $extraEnvSetsWorkerAuth = true -}}
+{{- end -}}
+{{- end -}}
{{- if not (hasKey $bundleCfg "minReplicas") }}
{{- fail (printf "workers.pools.%s.bundles.%s: missing required `minReplicas`." $poolName $bundleName) }}
{{- end }}
@@ -458,6 +472,20 @@ spec:
{{- end }}
- name: SIE_THRESHOLD_ROUTING_ENABLED
value: {{ dig "thresholdRouting" "enabled" false $root.Values.gateway | quote }}
+ {{- if ne $engine "candle" }}
+ {{- if $workerAuthEnforced }}
+ - name: SIE_AUTH_MODE
+ value: "token"
+ - name: SIE_AUTH_TOKEN
+ valueFrom:
+ secretKeyRef:
+ name: {{ include "sie-cluster.workers.authTokenSecretName" $root }}
+ key: {{ include "sie-cluster.workers.authTokenSecretKey" $root }}
+ {{- else if not $extraEnvSetsWorkerAuth }}
+ - name: SIE_AUTH_MODE
+ value: "none"
+ {{- end }}
+ {{- end }}
{{- if $root.Values.workers.common.workerSidecar.enabled }}
# worker-sidecar owns the NATS loop; the adapter process
# exposes the IPC server over a shared Unix socket. The chart fails render
@@ -593,12 +621,12 @@ spec:
value: {{ $workerLivenessBudgetS | quote }}
- name: SIE_GATEWAY_URL
value: {{ include "sie-cluster.gateway.internalUrl" $root | quote }}
- {{- if $root.Values.gateway.auth.tokenSecretName }}
+ {{- with include "sie-cluster.gateway.tokenSecretName" $root }}
- name: SIE_GATEWAY_API_KEY
valueFrom:
secretKeyRef:
- name: {{ $root.Values.gateway.auth.tokenSecretName }}
- key: {{ $root.Values.gateway.auth.tokenSecretKey }}
+ name: {{ . }}
+ key: {{ include "sie-cluster.gateway.tokenSecretKey" $root }}
{{- end }}
- name: SIE_WORKER_ID
valueFrom:
diff --git a/deploy/helm/sie-cluster/templates/worker-token-secret.yaml b/deploy/helm/sie-cluster/templates/worker-token-secret.yaml
new file mode 100644
index 000000000..c505a8a17
--- /dev/null
+++ b/deploy/helm/sie-cluster/templates/worker-token-secret.yaml
@@ -0,0 +1,3 @@
+{{- if include "sie-cluster.workers.generatesAuthToken" . }}
+{{- include "sie-cluster.config.generatedTokenSecret" (dict "root" . "name" (include "sie-cluster.workers.generatedAuthTokenSecretName" .) "key" (include "sie-cluster.workers.authTokenSecretKey" .) "keySetting" "workers.auth.tokenSecretKey" "nameSetting" "workers.auth.tokenSecretName" "labels" "sie-cluster.worker.labels") }}
+{{- end }}
diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yaml
index 681d62943..f62070ce7 100644
--- a/deploy/helm/sie-cluster/values.yaml
+++ b/deploy/helm/sie-cluster/values.yaml
@@ -325,17 +325,42 @@ gateway:
# -- Gateway auth (static token). The gateway does not receive the sie-config
# admin token; it holds only the sie-config read token (config.auth).
+ # 0.13.0 changes the defaults to mode token with a generated token
+ # (generateToken: true); see "Securing the cluster" in the chart README.
auth:
- # -- Mode: none | static
+ # -- Mode: none | static | token (static and token both enforce the tokens)
mode: none
- # -- Secret with comma-separated tokens
+ # -- Secret with comma-separated tokens. When set, it is used unchanged and
+ # no Secret is generated. Worker sidecars receive it as SIE_GATEWAY_API_KEY
+ # and present its first token to the gateway. It must not name the Secret
+ # and key of a checked credential, such as the Hugging Face
+ # token, a NATS password, the gateway admin token, either sie-config token,
+ # an image pull secret, an oauth2-proxy secret, the Better Stack token, the
+ # bundled same-namespace Grafana admin key, MCP connector secrets, or an
+ # ingress TLS key (the render fails). Other optional dependency credentials
+ # and arbitrary subchart env/volume refs need operator separation; see #767.
tokenSecretName: ""
tokenSecretKey: "SIE_AUTH_TOKEN"
+ # -- Generate the gateway token (a boolean). When tokenSecretName is empty,
+ # create `<fullname>-gateway-token` with a random 64-character token under
+ # tokenSecretKey. An existing Secret of that name keeps its token across
+ # upgrades (the render fails if the token is missing or shorter than 32
+ # characters), and the Secret is kept on uninstall
+ # (helm.sh/resource-policy: keep). Renderers without cluster access
+ # (`helm template`, GitOps controllers) cannot read the existing Secret and
+ # produce a new token on every render; use tokenSecretName there. The
+ # gateway enforces the token only with mode token or static. With mode none
+ # the Secret is created and given to the worker sidecars but not to the
+ # gateway, so clients can read the token before a second upgrade sets mode
+ # token. A mode set by a gateway.extraEnv valueFrom is unknown at render
+ # time, and the gateway then receives the token.
+ generateToken: false
# -- Existing Secret with the gateway admin token (key:
# adminTokenSecretKey). With mode token or static, the gateway requires it
# on POST, PUT, and DELETE under /v1/pools, /v1/admin, and /v1/configs;
# when empty, those requests get 403. It must not name the Secret and key
- # of either sie-config token (the render fails).
+ # of either sie-config token or the gateway client token (the render
+ # fails).
adminTokenSecretName: ""
adminTokenSecretKey: "SIE_ADMIN_TOKEN"
@@ -883,13 +908,49 @@ workers:
cpu: "2"
memory: "2Gi"
+ # -- Worker API authentication. When enabled, the gateway presents the
+ # worker token (SIE_WORKER_AUTH_TOKEN) and each worker container that serves
+ # the worker API requires it (SIE_AUTH_MODE=token, SIE_AUTH_TOKEN) on every
+ # route except the probes /healthz, /livez, and /readyz. It needs sie-server
+ # and sie-gateway images from this chart's release (appVersion) or later:
+ # images of 0.10.1 and earlier ignore these variables and serve without a
+ # token. A post-install and post-upgrade hook Job fails the release when a
+ # ready worker of the current revision answers GET /v1/models without a
+ # token or does not answer; the worker NetworkPolicies admit that Job's pod.
+ # With worker auth off, the chart sets SIE_AUTH_MODE=none on those
+ # containers. 0.13.0 changes the default to true; see "Securing the cluster"
+ # in the chart README.
+ auth:
+ # -- Require the worker token (a boolean).
+ enabled: false
+ # -- With enabled, the gateway presents the token but the workers do not
+ # require it yet (a boolean). A temporary aid for the two-step upgrade:
+ # once every gateway pod has restarted, upgrade again with
+ # `--set workers.auth.allowUnauthenticated=false`; `--reuse-values` and
+ # `--reset-then-reuse-values` keep it on. It fails the render without
+ # enabled.
+ allowUnauthenticated: false
+ # -- Existing Secret with the worker token (key: tokenSecretKey). When
+ # set, it is used unchanged. When empty, the chart creates
+ # `<fullname>-worker-token` with a random 64-character token, with the
+ # same reuse check, keep policy, and `helm template` caveat as
+ # gateway.auth.generateToken. It must not name the Secret and key of any
+ # checked credential listed under gateway.auth, including the gateway client
+ # token (the render fails). The key may hold comma-separated tokens: the workers
+ # accept each, and the gateway presents the first.
+ tokenSecretName: ""
+ tokenSecretKey: "SIE_AUTH_TOKEN"
+
# -- 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. A remote lane
+ # this release's gateway pods to the worker HTTP ports (the worker API
+ # requires no token unless workers.auth is enabled) and, while the workers
+ # require the token, the pods of the release-time worker token test (label
+ # app.kubernetes.io/component: worker-auth); 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, and
+ # 0.13.0 changes the default to true. A remote lane
# (workers.pools.remote) requires this policy or workers.remote.networkPolicy.
# When workers.remote.networkPolicy is enabled, this policy excludes remote
# lanes. Otherwise extraIngress must be empty, because any pod that reaches
@@ -929,7 +990,8 @@ workers:
equivalence:
configMap: ""
# -- NetworkPolicy for the remote lanes' pods, rendered whenever a remote
- # lane is enabled. Ingress: only this release's gateway pods, on the worker
+ # lane is enabled. Ingress: this release's gateway pods and, while the
+ # workers require the token, the worker token test's pods, on the worker
# ports; the generic workers.networkPolicy then excludes the remote lanes.
# Egress: DNS to dnsTo; this release's NATS, sie-config, gateway,
# telemetry collector and bundled Tempo; and TCP 443 plus each upstream's
diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.md
index 1ef849a45..65a249da3 100644
--- a/packages/sie_gateway/README.md
+++ b/packages/sie_gateway/README.md
@@ -97,7 +97,7 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio
| `SIE_AUTH_TOKEN` | | Singular alias for `SIE_AUTH_TOKENS` (fallback only; prefer the plural form) |
| `SIE_ADMIN_TOKEN` | | Admin bearer token the gateway requires inbound for admin-gated mutations: `POST/PUT/DELETE` on `/v1/configs/*`, `/v1/admin/*`, `/v1/pools/*`. If empty and an inbound request targets one of those paths, the middleware fails closed with `403`. Sent to `sie-config` only when `SIE_CONFIG_SERVICE_TOKEN` is unset (deprecated fallback) |
| `SIE_CONFIG_SERVICE_TOKEN` | | Bearer token the gateway presents **as a client** on its `sie-config` reads (`/v1/configs/bundles`, `/export`, `/epoch`): `sie-config`'s read-scoped `SIE_CONFIG_READ_TOKEN`. When set, it decides and a blank value sends no token; when unset, the gateway falls back to `SIE_ADMIN_TOKEN` and logs a deprecation warning |
-| `SIE_WORKER_AUTH_TOKEN` | | Token the gateway presents as `Authorization: Bearer` when it dials a worker's `/ws/status` (`ws` health mode). Set it to the workers' `SIE_AUTH_TOKEN` when workers require a token. The dial uses plain `ws://`, so the token crosses the network unencrypted: keep the gateway-to-worker network trusted. Startup fails when it is not a valid header value |
+| `SIE_WORKER_AUTH_TOKEN` | | Token the gateway presents as `Authorization: Bearer` when it dials a worker's `/ws/status` (`ws` health mode). Set it to the workers' `SIE_AUTH_TOKEN` when workers require a token. Like that variable it may list comma-separated tokens; the gateway presents the first. The dial uses plain `ws://`, so the token crosses the network unencrypted: keep the gateway-to-worker network trusted. Startup fails when it is not a valid header value |
| `SIE_AUTH_EXEMPT_OPERATIONAL` | `false` | When `true`, `/`, `/health`, and `/ws/*` are exempt from auth (they expose worker URLs, queue depth, GPU inventory). `/healthz` and `/readyz` are always exempt (K8s probes carry no creds). Default is fail-closed |
| `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` | `sie-config` | CSV allowlist of `producer_id` values trusted to publish on `sie.config.models._all`. Matches exact OR K8s pod-name prefix (`sie-config` also matches `sie-config-5f7b6d8c-kxwvr`). Untrusted notifications are dropped; the epoch poller still closes the gap |
| `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` | `false` | Disable producer validation entirely (dev/local only). `main` emits a startup audit warning when on |
diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rs
index 003c31079..ab3a453f6 100644
--- a/packages/sie_gateway/src/config.rs
+++ b/packages/sie_gateway/src/config.rs
@@ -786,15 +786,21 @@ fn env_default(key: &str, fallback: &str) -> String {
}
/// The `Authorization` value the gateway presents when it dials a worker's
-/// `/ws/status`, from `SIE_WORKER_AUTH_TOKEN`. `None` when it is unset or blank.
+/// `/ws/status`, from `SIE_WORKER_AUTH_TOKEN`. Like the workers' own
+/// `SIE_AUTH_TOKEN`, the value may list comma-separated tokens; the gateway
+/// presents the first. `None` when it holds no token.
pub fn worker_authorization_from_env() -> Result<Option<HeaderValue>, String> {
- worker_authorization(env::var("SIE_WORKER_AUTH_TOKEN").unwrap_or_default().trim())
+ worker_authorization(&env::var("SIE_WORKER_AUTH_TOKEN").unwrap_or_default())
}
-fn worker_authorization(token: &str) -> Result<Option<HeaderValue>, String> {
- if token.is_empty() {
+fn worker_authorization(tokens: &str) -> Result<Option<HeaderValue>, String> {
+ let Some(token) = tokens
+ .split(',')
+ .map(str::trim)
+ .find(|token| !token.is_empty())
+ else {
return Ok(None);
- }
+ };
let mut value = HeaderValue::from_str(&format!("Bearer {token}"))
.map_err(|_| "SIE_WORKER_AUTH_TOKEN is not a valid HTTP header value".to_string())?;
value.set_sensitive(true);
@@ -2404,6 +2410,23 @@ mod tests {
);
}
+ #[test]
+ fn worker_authorization_presents_the_first_listed_token() {
+ for (tokens, expected) in [
+ ("new,old", Some("Bearer new")),
+ (" new , old ", Some("Bearer new")),
+ (",new", Some("Bearer new")),
+ (" , ", None),
+ ] {
+ let value = worker_authorization(tokens).unwrap();
+ assert_eq!(
+ value.as_ref().map(|value| value.to_str().unwrap()),
+ expected,
+ "{tokens:?}"
+ );
+ }
+ }
+
fn cfg_on_host(host: &str, mode: &str, tokens: Vec<&str>) -> Config {
let mut cfg = cfg_with_auth(mode, tokens, "", false);
cfg.host = host.to_string();
diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rs
index 432fc2569..f1c0bfcec 100644
--- a/packages/sie_server_sidecar/src/main.rs
+++ b/packages/sie_server_sidecar/src/main.rs
@@ -78,7 +78,8 @@ struct Cli {
#[arg(long, env = "SIE_GATEWAY_URL")]
gateway_url: Option<String>,
- /// Bearer token for gateway pool-status reads.
+ /// Bearer token for gateway pool-status reads. The gateway reads its own
+ /// token setting as a comma-separated list; the first token is presented.
#[arg(long, env = "SIE_GATEWAY_API_KEY", hide_env_values = true)]
gateway_api_key: Option<String>,
@@ -228,7 +229,7 @@ async fn main() -> anyhow::Result<()> {
model_ready_timeout_s,
payload_store_url: cli.payload_store_url,
gateway_url: cli.gateway_url.filter(|url| !url.trim().is_empty()),
- gateway_api_key: cli.gateway_api_key.filter(|token| !token.trim().is_empty()),
+ gateway_api_key: gateway_api_key(cli.gateway_api_key.as_deref()),
pool_admission_enabled: env_bool_value(cli.pool_admission_enabled.as_deref(), true),
pool_admission_check_interval_ms: seconds_to_millis(
cli.pool_admission_check_interval_s,
@@ -438,10 +439,20 @@ fn validate_model_ready_liveness_budget(
Ok(())
}
+/// The token presented to the gateway: the first non-empty entry of a
+/// comma-separated list, which is how the gateway reads its own tokens.
+fn gateway_api_key(raw: Option<&str>) -> Option<String> {
+ raw?.split(',')
+ .map(str::trim)
+ .find(|token| !token.is_empty())
+ .map(str::to_string)
+}
+
#[cfg(test)]
mod tests {
use std::path::PathBuf;
+ use super::gateway_api_key;
use super::parse_ipc_socket_paths;
use super::resolve_config_service_token;
use super::validate_ingest_mode;
@@ -452,6 +463,25 @@ mod tests {
use super::IngestMode;
use clap::CommandFactory;
+ #[test]
+ fn gateway_api_key_presents_the_first_listed_token() {
+ assert_eq!(
+ gateway_api_key(Some("new-token")).as_deref(),
+ Some("new-token")
+ );
+ assert_eq!(
+ gateway_api_key(Some(" new-token , old-token ")).as_deref(),
+ Some("new-token")
+ );
+ assert_eq!(
+ gateway_api_key(Some(",, new-token,")).as_deref(),
+ Some("new-token")
+ );
+ assert_eq!(gateway_api_key(Some(" , ")), None);
+ assert_eq!(gateway_api_key(Some("")), None);
+ assert_eq!(gateway_api_key(None), None);
+ }
+
#[test]
fn secret_env_args_hide_their_values() {
let command = Cli::command();
diff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.py
index 44daaee28..dd1ed5659 100644
--- a/tools/ci/tests/test_helm_render.py
+++ b/tools/ci/tests/test_helm_render.py
@@ -7,6 +7,7 @@ import re
import shutil
import socket
import subprocess
+import sys
import time
import urllib.request
from pathlib import Path
@@ -2891,3 +2892,956 @@ def test_threshold_long_name_keeps_control_resources_and_gateway_url_aligned(tmp
gateway = next(doc for doc in yaml.safe_load_all(gateway_result.stdout) if doc and doc["kind"] == "Deployment")
env = {item["name"]: item for item in gateway["spec"]["template"]["spec"]["containers"][0]["env"]}
assert env["SIE_THRESHOLD_NATS_URL"]["value"] == f"nats://{name}:4222"
+
+
+GATEWAY_TOKEN_SECRET = "sie-sie-cluster-gateway-token"
+WORKER_TOKEN_SECRET = "sie-sie-cluster-worker-token"
+GENERATED_GATEWAY_TOKEN = {"name": GATEWAY_TOKEN_SECRET, "key": "SIE_AUTH_TOKEN"}
+GENERATED_WORKER_TOKEN = {"name": WORKER_TOKEN_SECRET, "key": "SIE_AUTH_TOKEN"}
+GENERATED_ADMIN_TOKEN_REF = {"tokenSecretName": GENERATED_ADMIN_TOKEN_SECRET, "tokenSecretKey": "SIE_ADMIN_TOKEN"}
+GENERATED_READ_TOKEN_REF = {"tokenSecretName": GENERATED_READ_TOKEN_SECRET, "tokenSecretKey": "SIE_CONFIG_READ_TOKEN"}
+L4_WORKER = "sie-sie-cluster-worker-l4-default/worker"
+L4_SIDECAR = "sie-sie-cluster-worker-l4-default/worker-sidecar"
+# Values as `helm upgrade --reuse-values` sees them from a release that predates
+# these keys: null removes the chart default.
+PREDATING_GATEWAY_AND_WORKER_TOKEN_KEYS = {
+ "gateway": {"auth": {"generateToken": None}},
+ "workers": {"auth": None, **L4_POOL["workers"]},
+}
+
+
+def secret_names(docs: list[dict]) -> set[str]:
+ return {doc["metadata"]["name"] for doc in docs if doc["kind"] == "Secret"}
+
+
+def generated_token(docs: list[dict], name: str, component: str) -> str:
+ (secret,) = [doc for doc in docs if doc["kind"] == "Secret" and doc["metadata"]["name"] == name]
+ assert secret["metadata"]["labels"]["app.kubernetes.io/component"] == component
+ return secret_token(secret, "SIE_AUTH_TOKEN")
+
+
[email protected]("values", [L4_POOL, PREDATING_GATEWAY_AND_WORKER_TOKEN_KEYS])
+def test_gateway_and_worker_tokens_are_off_by_default(tmp_path: Path, values: dict) -> None:
+ docs = rendered_documents(tmp_path, values)
+ assert {GATEWAY_TOKEN_SECRET, WORKER_TOKEN_SECRET}.isdisjoint(secret_names(docs))
+ assert env_entries(docs, "SIE_AUTH_MODE") == {GATEWAY: "none", L4_WORKER: "none"}
+ for name in ("SIE_AUTH_TOKEN", "SIE_AUTH_TOKENS", "SIE_GATEWAY_API_KEY", "SIE_WORKER_AUTH_TOKEN"):
+ assert env_entries(docs, name) == {}
+
+
+def test_generated_gateway_token_with_auth_mode_none_reaches_only_the_worker_sidecars(tmp_path: Path) -> None:
+ docs = rendered_documents(tmp_path, {**L4_POOL, "gateway": {"auth": {"generateToken": True}}})
+ generated_token(docs, GATEWAY_TOKEN_SECRET, "gateway")
+ assert env_entries(docs, "SIE_AUTH_MODE") == {GATEWAY: "none", L4_WORKER: "none"}
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {}
+ assert env_entries(docs, "SIE_GATEWAY_API_KEY") == {L4_SIDECAR: GENERATED_GATEWAY_TOKEN}
+
+
[email protected]("mode", ["token", "static"])
+def test_generated_gateway_token_is_wired_to_every_consumer_with_token_auth(tmp_path: Path, mode: str) -> None:
+ gateway = {"auth": {"mode": mode, "generateToken": True}}
+ docs = rendered_documents(tmp_path, ingress_values(SCOPED_TLS, gateway=gateway, workers=L4_POOL["workers"]))
+ generated_token(docs, GATEWAY_TOKEN_SECRET, "gateway")
+ assert env_entries(docs, "SIE_AUTH_MODE") == {GATEWAY: mode, L4_WORKER: "none"}
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {GATEWAY: GENERATED_GATEWAY_TOKEN}
+ assert env_entries(docs, "SIE_GATEWAY_API_KEY") == {L4_SIDECAR: GENERATED_GATEWAY_TOKEN}
+ assert len(gateway_ingresses(docs)) == 1
+
+
+def test_operator_gateway_token_secret_keeps_its_extra_env_token_override(tmp_path: Path) -> None:
+ extra_env = [{"name": "SIE_AUTH_TOKENS", "value": "override"}]
+ values = {**L4_POOL, "gateway": {**GATEWAY_AUTH, "extraEnv": extra_env}}
+ docs = rendered_documents(tmp_path, values)
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {GATEWAY: {"name": "sie-gateway-auth", "key": "SIE_AUTH_TOKEN"}}
+ assert env_entries(docs, "SIE_AUTH_TOKENS") == {GATEWAY: "override"}
+
+
[email protected]("generate", [False, True])
+def test_operator_gateway_token_secret_is_used_unchanged(tmp_path: Path, generate: bool) -> None:
+ auth = {"mode": "static", "tokenSecretName": "sie-gateway-auth", "tokenSecretKey": "tokens"}
+ docs = rendered_documents(tmp_path, {**L4_POOL, "gateway": {"auth": {**auth, "generateToken": generate}}})
+ assert GATEWAY_TOKEN_SECRET not in secret_names(docs)
+ operator = {"name": "sie-gateway-auth", "key": "tokens"}
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {GATEWAY: operator}
+ assert env_entries(docs, "SIE_GATEWAY_API_KEY") == {L4_SIDECAR: operator}
+
+
+def test_worker_auth_requires_the_token_on_every_container_that_serves_the_worker_api(tmp_path: Path) -> None:
+ pools = {
+ "l4": {"enabled": True, "gpu": {"count": 2}},
+ "cpu": {
+ "enabled": True,
+ "bundles": {"candle": {"engine": "candle", "minReplicas": 0, "maxReplicas": 1}},
+ },
+ }
+ docs = rendered_documents(tmp_path, {"workers": {"auth": {"enabled": True}, "pools": pools}})
+ generated_token(docs, WORKER_TOKEN_SECRET, "worker")
+ servers = [
+ "sie-sie-cluster-worker-l4-default/worker-0",
+ "sie-sie-cluster-worker-l4-default/worker-1",
+ "sie-sie-cluster-worker-cpu-default/worker",
+ ]
+ assert "sie-sie-cluster-worker-cpu-candle/worker" in env_entries(docs, "SIE_BUNDLE")
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == dict.fromkeys(servers, GENERATED_WORKER_TOKEN)
+ assert env_entries(docs, "SIE_AUTH_MODE") == {GATEWAY: "none", **dict.fromkeys(servers, "token")}
+ assert env_entries(docs, "SIE_WORKER_AUTH_TOKEN") == {GATEWAY: GENERATED_WORKER_TOKEN}
+
+
+def test_worker_auth_covers_the_remote_lane(tmp_path: Path) -> None:
+ values = remote_pool_values()
+ values["workers"]["auth"] = {"enabled": True}
+ tokens = env_entries(rendered_documents(tmp_path, values), "SIE_AUTH_TOKEN")
+ assert tokens["sie-sie-cluster-worker-remote-remote/worker"] == GENERATED_WORKER_TOKEN
+
+
+def test_worker_auth_upgrade_aid_gives_the_token_only_to_the_gateway(tmp_path: Path) -> None:
+ auth = {"enabled": True, "allowUnauthenticated": True}
+ docs = rendered_documents(tmp_path, {"workers": {"auth": auth, **L4_POOL["workers"]}})
+ generated_token(docs, WORKER_TOKEN_SECRET, "worker")
+ assert env_entries(docs, "SIE_WORKER_AUTH_TOKEN") == {GATEWAY: GENERATED_WORKER_TOKEN}
+ assert env_entries(docs, "SIE_AUTH_MODE") == {GATEWAY: "none", L4_WORKER: "none"}
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {}
+
+
+def test_operator_worker_token_secret_is_used_unchanged(tmp_path: Path) -> None:
+ auth = {"enabled": True, "tokenSecretName": "sie-worker-auth", "tokenSecretKey": "token"}
+ docs = rendered_documents(tmp_path, {"workers": {"auth": auth, **L4_POOL["workers"]}})
+ assert WORKER_TOKEN_SECRET not in secret_names(docs)
+ operator = {"name": "sie-worker-auth", "key": "token"}
+ assert env_entries(docs, "SIE_WORKER_AUTH_TOKEN") == {GATEWAY: operator}
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {L4_WORKER: operator}
+
+
+def test_worker_network_policy_admits_the_gateway_with_worker_auth(tmp_path: Path) -> None:
+ workers = {"auth": {"enabled": True}, "networkPolicy": {"enabled": True}, **L4_POOL["workers"]}
+ (policy,) = worker_network_policies(rendered_documents(tmp_path, {"workers": workers}))
+ (rule,) = policy["spec"]["ingress"]
+ gateway, _ = rule["from"]
+ assert gateway["podSelector"]["matchLabels"]["app.kubernetes.io/component"] == "gateway"
+ assert [port["port"] for port in rule["ports"]] == [8080]
+
+
+ ("values", "error"),
+ [
+ (
+ {"workers": {"auth": {"allowUnauthenticated": True}}},
+ "workers.auth.allowUnauthenticated=true needs workers.auth.enabled=true",
+ ),
+ (
+ {
+ "gateway": {"auth": {"generateToken": True}},
+ "workers": {"auth": {"enabled": True, "tokenSecretName": GATEWAY_TOKEN_SECRET}},
+ },
+ "The worker token and the gateway client token are the same Secret key",
+ ),
+ (
+ {"gateway": GATEWAY_AUTH, "workers": {"auth": {"enabled": True, "tokenSecretName": "sie-gateway-auth"}}},
+ "The worker token and the gateway client token are the same Secret key",
+ ),
+ (
+ {
+ "gateway": {"auth": {"adminTokenSecretName": "gateway-admin"}},
+ "workers": {
+ "auth": {"enabled": True, "tokenSecretName": "gateway-admin", "tokenSecretKey": "SIE_ADMIN_TOKEN"}
+ },
+ },
+ "The worker token and the gateway admin token are the same Secret key",
+ ),
+ (
+ {"workers": {"auth": {"enabled": True, **GENERATED_ADMIN_TOKEN_REF}}},
+ "The worker token and the sie-config admin token are the same Secret key",
+ ),
+ (
+ {"workers": {"auth": {"enabled": True, **GENERATED_READ_TOKEN_REF}}},
+ "The worker token and the sie-config read token are the same Secret key",
+ ),
+ (
+ {"gateway": {"auth": {"mode": "token", **GENERATED_ADMIN_TOKEN_REF}}},
+ "The gateway client token and the sie-config admin token are the same Secret key",
+ ),
+ (
+ {"gateway": {"auth": {"mode": "token", **GENERATED_READ_TOKEN_REF}}},
+ "The gateway client token and the sie-config read token are the same Secret key",
+ ),
+ (
+ {
+ "gateway": {
+ "auth": {
+ "generateToken": True,
+ "adminTokenSecretName": GATEWAY_TOKEN_SECRET,
+ "adminTokenSecretKey": "SIE_AUTH_TOKEN",
+ }
+ }
+ },
+ "The gateway client token and the gateway admin token are the same Secret key",
+ ),
+ ({"gateway": {"auth": {"generateToken": "true"}}}, "gateway.auth.generateToken must be a boolean"),
+ ({"workers": {"auth": {"enabled": "false"}}}, "workers.auth.enabled must be a boolean"),
+ (
+ {"workers": {"auth": {"enabled": True, "allowUnauthenticated": "true"}}},
+ "workers.auth.allowUnauthenticated must be a boolean",
+ ),
+ ({"gateway": {"auth": {"generateToken": True, "tokenSecretKey": " "}}}, "gateway.auth.tokenSecretKey is empty"),
+ ({"workers": {"auth": {"enabled": True, "tokenSecretKey": ""}}}, "workers.auth.tokenSecretKey is empty"),
+ (
+ {
+ "gateway": {"extraEnv": [{"name": "SIE_WORKER_AUTH_TOKEN", "value": "override"}]},
+ "workers": {"auth": {"enabled": True}},
+ },
+ "gateway.extraEnv must not override chart-owned variable SIE_WORKER_AUTH_TOKEN",
+ ),
+ (
+ {
+ "workers": {
+ "auth": {"enabled": True},
+ "common": {"extraEnv": [{"name": "SIE_AUTH_MODE", "value": "none"}]},
+ }
+ },
+ "workers.common.extraEnv must not override chart-owned variable SIE_AUTH_MODE",
+ ),
+ (
+ {
+ "workers": {
+ "auth": {"enabled": True},
+ "common": {"extraEnv": [{"name": "SIE_AUTH_TOKENS", "value": "override"}]},
+ }
+ },
+ "workers.common.extraEnv must not override chart-owned variable SIE_AUTH_TOKENS",
+ ),
+ (
+ {
+ "gateway": {
+ "auth": {"mode": "token", "generateToken": True},
+ "extraEnv": [{"name": "SIE_AUTH_TOKENS", "value": "override"}],
+ }
+ },
+ "gateway.extraEnv must not override chart-owned variable SIE_AUTH_TOKENS",
+ ),
+ (
+ {
+ "gateway": {"auth": {"generateToken": True}},
+ "workers": {
+ "common": {"hfCache": {"tokenSecret": GATEWAY_TOKEN_SECRET, "tokenSecretKey": "SIE_AUTH_TOKEN"}}
+ },
+ },
+ "The gateway client token and the Hugging Face token are the same Secret key",
+ ),
+ (
+ {
+ "workers": {
+ "auth": {"enabled": True, "tokenSecretName": "sie-nats-auth-worker", "tokenSecretKey": "password"}
+ }
+ },
+ "The worker token and the NATS worker password are the same Secret key",
+ ),
+ ],
+)
+def test_unsafe_gateway_and_worker_token_values_fail_the_render(tmp_path: Path, values: dict, error: str) -> None:
+ workers = {**L4_POOL["workers"], **values.get("workers", {})}
+ assert error in render_error(tmp_path, {**values, "workers": workers})
+
+
+ ("values", "api_key_secret", "owner"),
+ [
+ (
+ {"gateway": {"auth": {"generateToken": True}}},
+ {"name": GATEWAY_TOKEN_SECRET, "key": "SIE_AUTH_TOKEN"},
+ "the generated gateway client token",
+ ),
+ (
+ {"workers": {"auth": {"enabled": True}}},
+ {"name": WORKER_TOKEN_SECRET, "key": "SIE_AUTH_TOKEN"},
+ "the generated worker token",
+ ),
+ (
+ {"workers": {"auth": {"enabled": True, "tokenSecretName": "team-upstream", "tokenSecretKey": "api-key"}}},
+ {"name": "team-upstream", "key": "api-key"},
+ "workers.auth.tokenSecretName",
+ ),
+ ],
+)
+def test_an_upstream_key_cannot_be_the_gateway_client_or_worker_token(
+ tmp_path: Path, values: dict, api_key_secret: dict, owner: str
+) -> None:
+ result = render_workers(tmp_path, {**values, "upstreams": {"team": upstream(api_key_secret=api_key_secret)}})
+ assert result.returncode != 0
+ assert f"upstreams.team.api_key_secret and {owner} name the same Secret key" in result.stderr
+
+
+WORKER_AUTH_TEST_JOB = "sie-sie-cluster-worker-auth-test-1"
+
+
+def worker_with(**auth: object) -> dict:
+ return {"auth": {"enabled": True, **auth}, **L4_POOL["workers"]}
+
+
+ ("values", "error"),
+ [
+ (
+ {"workers": worker_with(tokenSecretName="oauth2-proxy", tokenSecretKey="OAUTH2_PROXY_COOKIE_SECRET")},
+ "The worker token and the oauth2-proxy cookieSecretKey are the same Secret key",
+ ),
+ (
+ {
+ "gateway": {
+ "auth": {
+ "mode": "token",
+ "tokenSecretName": "oauth2-proxy",
+ "tokenSecretKey": "OAUTH2_PROXY_CLIENT_SECRET",
+ }
+ }
+ },
+ "The gateway client token and the oauth2-proxy clientSecretKey are the same Secret key",
+ ),
+ (
+ {
+ "global": {"imagePullSecrets": ["regcred"]},
+ "workers": worker_with(tokenSecretName="regcred", tokenSecretKey=".dockerconfigjson"),
+ },
+ "The worker token and the image pull secret are the same Secret key",
+ ),
+ (
+ {
+ "mcpEdge": {"existingSecretName": "mcp-conn"},
+ "gateway": {
+ "auth": {"mode": "token", "tokenSecretName": "mcp-conn", "tokenSecretKey": "connector-secrets"}
+ },
+ },
+ "The gateway client token and the MCP connector secrets are the same Secret key",
+ ),
+ (
+ {
+ "observability": {"otel": {"collector": {"betterStack": {"existingSecret": "better-stack"}}}},
+ "workers": worker_with(tokenSecretName="better-stack", tokenSecretKey="token"),
+ },
+ "The worker token and the Better Stack token are the same Secret key",
+ ),
+ (
+ {
+ "mcpEdge": {"clusterApiKey": {"existingSecretName": "mcp-key"}},
+ "workers": worker_with(tokenSecretName="mcp-key", tokenSecretKey="api-key"),
+ },
+ "The worker token and the MCP edge cluster API key are the same Secret key",
+ ),
+ (
+ {
+ "mcpEdge": {"clusterApiKey": {"existingSecretName": "hf", "secretKey": "token"}},
+ "workers": {"common": {"hfCache": {"tokenSecret": "hf", "tokenSecretKey": "token"}}},
+ },
+ "The MCP edge cluster API key and the Hugging Face token are the same Secret key",
+ ),
+ (
+ {"workers": worker_with(tokenSecretName="sie-sie-cluster-mcp-tls", tokenSecretKey="tls.key")},
+ "The worker token and the MCP ingress TLS certificate are the same Secret key",
+ ),
+ (
+ {
+ "gateway": {
+ "auth": {"mode": "token"},
+ "extraEnv": [
+ {
+ "name": "SIE_AUTH_TOKENS",
+ "valueFrom": {"secretKeyRef": {"name": "client-tokens", "key": "tokens"}},
+ }
+ ],
+ },
+ "workers": worker_with(tokenSecretName="client-tokens", tokenSecretKey="tokens"),
+ },
+ "The worker token and the gateway client token from gateway.extraEnv SIE_AUTH_TOKENS are the same",
+ ),
+ (
+ {
+ "gateway": {
+ "auth": {"mode": "token"},
+ "extraEnv": [
+ {
+ "name": "SIE_AUTH_TOKEN",
+ "valueFrom": {"secretKeyRef": {"name": "sie-nats-auth-gateway", "key": "password"}},
+ }
+ ],
+ }
+ },
+ "gateway.extraEnv SIE_AUTH_TOKEN and the NATS gateway password are the same Secret key",
+ ),
+ ],
+)
+def test_client_and_worker_tokens_are_kept_apart_from_every_wired_secret_key(
+ tmp_path: Path, values: dict, error: str
+) -> None:
+ workers = {**L4_POOL["workers"], **values.get("workers", {})}
+ assert error in render_error(tmp_path, {**values, "workers": workers})
+
+
[email protected]("credential", ["worker", "gateway", "upstream"])
+ ("grafana", "secret_name", "secret_key"),
+ [
+ ({}, "sie-grafana", "admin-password"),
+ ({"admin": {"existingSecret": "grafana-admin"}}, "grafana-admin", "admin-user"),
+ (
+ {"admin": {"existingSecret": "{{ .Release.Name }}-admin", "passwordKey": "password"}},
+ "sie-admin",
+ "password",
+ ),
+ (
+ {"fullnameOverride": "dashboard", "admin": {"existingSecret": "{{ .Values.fullnameOverride }}"}},
+ "dashboard",
+ "admin-password",
+ ),
+ (
+ {"admin": {"existingSecret": "{{ .Values.admin.userKey }}-admin", "userKey": "dashboard"}},
+ "dashboard-admin",
+ "dashboard",
+ ),
+ ],
+)
+def test_inference_credentials_cannot_reuse_bundled_grafana_admin_keys(
+ tmp_path: Path, credential: str, grafana: dict, secret_name: str, secret_key: str
+) -> None:
+ values = {"kube-prometheus-stack": {"install": True, "grafana": grafana}}
+ if credential == "worker":
+ values["workers"] = worker_with(tokenSecretName=secret_name, tokenSecretKey=secret_key)
+ elif credential == "gateway":
+ values["gateway"] = {"auth": {"mode": "token", "tokenSecretName": secret_name, "tokenSecretKey": secret_key}}
+ else:
+ values["upstreams"] = {"team": upstream(api_key_secret={"name": secret_name, "key": secret_key})}
+ error = render_error(tmp_path, values)
+ assert "Grafana admin" in error
+ if credential == "upstream":
+ assert "upstreams.team.api_key_secret" in error
+ else:
+ assert f"{secret_name}/{secret_key}" in error
+
+
+ "stack",
+ [
+ {"install": False},
+ {"install": True, "grafana": {"enabled": False}},
+ {"install": True, "grafana": {"namespaceOverride": "monitoring"}},
+ {"install": True, "grafana": {"env": {"GF_SECURITY_ADMIN_PASSWORD": "fixture-password"}}},
+ {"install": True, "grafana": {"env": {"GF_SECURITY_ADMIN_PASSWORD__FILE": "/etc/grafana/password"}}},
+ {"install": True, "grafana": {"env": {"GF_SECURITY_DISABLE_INITIAL_ADMIN_CREATION": "true"}}},
+ ],
+)
+def test_grafana_admin_keys_only_reserve_credentials_actually_wired_in_the_worker_namespace(
+ tmp_path: Path, stack: dict
+) -> None:
+ values = {
+ "kube-prometheus-stack": stack,
+ "workers": worker_with(tokenSecretName="sie-grafana", tokenSecretKey="admin-password"),
+ }
+ result = render_workers(tmp_path, values)
+ assert result.returncode == 0, result.stderr
+
+
[email protected]("grafana_namespace", ["sie", "workers"])
+def test_grafana_admin_collision_uses_the_effective_worker_namespace(tmp_path: Path, grafana_namespace: str) -> None:
+ values = {
+ "global": {"namespace": "workers"},
+ "kube-prometheus-stack": {"install": True, "grafana": {"namespaceOverride": grafana_namespace}},
+ "workers": worker_with(tokenSecretName="sie-grafana", tokenSecretKey="admin-password"),
+ }
+ result = render_workers(tmp_path, values)
+ if grafana_namespace == "workers":
+ assert result.returncode != 0
+ assert "The worker token and the Grafana admin password are the same Secret key" in result.stderr
+ else:
+ assert result.returncode == 0, result.stderr
+
+
+def test_the_mcp_edge_may_present_the_gateway_client_token(tmp_path: Path) -> None:
+ values = {
+ **L4_POOL,
+ "gateway": {"auth": {"mode": "token", "generateToken": True}},
+ "mcpEdge": {
+ "enabled": True,
+ "clusterApiKey": {"existingSecretName": GATEWAY_TOKEN_SECRET, "secretKey": "SIE_AUTH_TOKEN"},
+ },
+ }
+ docs = rendered_documents(tmp_path, values)
+ assert env_entries(docs, "SIE_API_KEY") == {"sie-sie-cluster-mcp/mcp-edge": GENERATED_GATEWAY_TOKEN}
+
+
+def test_an_upstream_key_cannot_be_a_gateway_extra_env_token(tmp_path: Path) -> None:
+ secret_ref = {"secretKeyRef": {"name": "team-upstream", "key": "api-key"}}
+ values = {
+ "gateway": {"auth": {"mode": "token"}, "extraEnv": [{"name": "SIE_AUTH_TOKENS", "valueFrom": secret_ref}]},
+ "upstreams": {"team": upstream(api_key_secret={"name": "team-upstream", "key": "api-key"})},
+ }
+ result = render_workers(tmp_path, values)
+ assert result.returncode != 0
+ assert (
+ "upstreams.team.api_key_secret and gateway.extraEnv SIE_AUTH_TOKENS name the same Secret key" in result.stderr
+ )
+
+
+ "workers",
+ [
+ L4_POOL["workers"],
+ {"auth": {"enabled": True, "allowUnauthenticated": True}, **L4_POOL["workers"]},
+ ],
+)
+def test_workers_that_do_not_require_the_token_are_explicitly_open(tmp_path: Path, workers: dict) -> None:
+ pools = {
+ **workers["pools"],
+ "cpu": {"enabled": True, "bundles": {"candle": {"engine": "candle", "minReplicas": 0, "maxReplicas": 1}}},
+ }
+ docs = rendered_documents(tmp_path, {"workers": {**workers, "pools": pools}})
+ assert "sie-sie-cluster-worker-cpu-candle/worker" in env_entries(docs, "SIE_BUNDLE")
+ cpu_worker = "sie-sie-cluster-worker-cpu-default/worker"
+ assert env_entries(docs, "SIE_AUTH_MODE") == {GATEWAY: "none", L4_WORKER: "none", cpu_worker: "none"}
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {}
+
+
+def test_an_operator_worker_token_in_extra_env_is_not_overridden(tmp_path: Path) -> None:
+ extra_env = [{"name": "SIE_AUTH_TOKEN", "valueFrom": {"secretKeyRef": {"name": "own-worker", "key": "token"}}}]
+ docs = rendered_documents(tmp_path, {"workers": {"common": {"extraEnv": extra_env}, **L4_POOL["workers"]}})
+ assert env_entries(docs, "SIE_AUTH_MODE") == {GATEWAY: "none"}
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {L4_WORKER: {"name": "own-worker", "key": "token"}}
+
+
[email protected]("name", ["SIE_AUTH_MODE", "SIE_AUTH_TOKEN", "SIE_AUTH_TOKENS"])
+def test_worker_auth_variables_are_reserved_in_the_upgrade_step(tmp_path: Path, name: str) -> None:
+ workers = {
+ "auth": {"enabled": True, "allowUnauthenticated": True},
+ "common": {"extraEnv": [{"name": name, "value": "override"}]},
+ **L4_POOL["workers"],
+ }
+ error = render_error(tmp_path, {"workers": workers})
+ assert f"workers.common.extraEnv must not override chart-owned variable {name}" in error
+
+
+def test_the_sidecar_gateway_key_is_reserved_while_the_chart_wires_it(tmp_path: Path) -> None:
+ sidecar = {"workerSidecar": {"extraEnv": [{"name": "SIE_GATEWAY_API_KEY", "value": "override"}]}}
+ workers = {"common": sidecar, **L4_POOL["workers"]}
+ error = render_error(tmp_path, {"gateway": {"auth": {"generateToken": True}}, "workers": workers})
+ assert "workers.common.workerSidecar.extraEnv must not override chart-owned variable SIE_GATEWAY_API_KEY" in error
+ docs = rendered_documents(tmp_path, {"workers": workers})
+ assert env_entries(docs, "SIE_GATEWAY_API_KEY") == {L4_SIDECAR: "override"}
+
+
+MCP_TOKEN_AUTH = {"gateway": {"auth": {"mode": "token", "generateToken": True}}, "mcpEdge": {"enabled": True}}
+
+
+def test_the_mcp_edge_needs_a_gateway_token_when_the_gateway_requires_one(tmp_path: Path) -> None:
+ error = render_error(tmp_path, {**L4_POOL, **MCP_TOKEN_AUTH})
+ assert "mcpEdge.enabled with gateway token auth" in error
+ assert "needs mcpEdge.clusterApiKey.existingSecretName" in error
+ assert f"mcpEdge.clusterApiKey.existingSecretName={GATEWAY_TOKEN_SECRET}" in error
+
+
+RUNTIME_GATEWAY_MODE = {
+ "auth": {"generateToken": True},
+ "extraEnv": [{"name": "SIE_AUTH_MODE", "valueFrom": {"configMapKeyRef": {"name": "gateway-mode", "key": "mode"}}}],
+}
+
+
+def test_the_mcp_edge_needs_a_gateway_token_when_the_gateway_mode_is_known_only_at_run_time(tmp_path: Path) -> None:
+ error = render_error(tmp_path, {**L4_POOL, "gateway": RUNTIME_GATEWAY_MODE, "mcpEdge": {"enabled": True}})
+ assert "or a gateway auth mode known only at run time" in error
+ assert f"mcpEdge.clusterApiKey.existingSecretName={GATEWAY_TOKEN_SECRET}" in error
+
+
+def rendered_notes(tmp_path: Path, values: dict) -> str:
+ chart = tmp_path / "notes-chart"
+ shutil.copytree(helm.CHART_DIR, chart)
+ notes = (chart / "templates" / "NOTES.txt").read_text(encoding="utf-8")
+ (chart / "templates" / "NOTES.txt").unlink()
+ (chart / "templates" / "_notes_under_test.tpl").write_text(
+ '{{- define "notes.under.test" -}}\n' + notes + "\n{{- end -}}\n", encoding="utf-8"
+ )
+ (chart / "templates" / "notes-under-test.yaml").write_text(
+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: notes-under-test\n"
+ 'data:\n notes: {{ include "notes.under.test" . | quote }}\n',
+ encoding="utf-8",
+ )
+ values_file = tmp_path / "notes-values.yaml"
+ values_file.write_text(yaml.safe_dump(values), encoding="utf-8")
+ result = subprocess.run(
+ [
+ "mise",
+ "exec",
+ "--",
+ "helm",
+ "template",
+ "sie",
+ str(chart),
+ "--namespace",
+ "sie",
+ "-f",
+ str(values_file),
+ "--show-only",
+ "templates/notes-under-test.yaml",
+ ],
+ cwd=ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ return yaml.safe_load(result.stdout)["data"]["notes"]
+
+
+def test_the_notes_say_when_the_gateway_mode_is_known_only_at_run_time(tmp_path: Path) -> None:
+ notes = rendered_notes(tmp_path, {**L4_POOL, "gateway": RUNTIME_GATEWAY_MODE})
+ assert "known only at run time" in notes
+ assert "does not require this token yet" not in notes
+ assert "does not require this token yet (gateway auth mode none)" in rendered_notes(
+ tmp_path / "none", {**L4_POOL, "gateway": {"auth": {"generateToken": True}}}
+ )
+
+
+ "values",
+ [
+ {"gateway": {"auth": {"generateToken": True}}, "mcpEdge": {"enabled": True}},
+ {**MCP_TOKEN_AUTH, "mcpEdge": {"enabled": True, "clusterBaseUrl": "https://gateway.example.com"}},
+ {
+ **MCP_TOKEN_AUTH,
+ "mcpEdge": {"enabled": True, "clusterApiKey": {"existingSecretName": "mcp-key", "secretKey": "token"}},
+ },
+ ],
+)
+def test_the_mcp_edge_renders_when_it_has_what_its_gateway_needs(tmp_path: Path, values: dict) -> None:
+ rendered_documents(tmp_path, {**L4_POOL, **values})
+
+
+def test_a_gateway_mode_from_value_from_gets_the_generated_token(tmp_path: Path) -> None:
+ mode = {"name": "SIE_AUTH_MODE", "valueFrom": {"configMapKeyRef": {"name": "gateway-auth", "key": "mode"}}}
+ docs = rendered_documents(tmp_path, {**L4_POOL, "gateway": {"auth": {"generateToken": True}, "extraEnv": [mode]}})
+ assert env_entries(docs, "SIE_AUTH_TOKEN") == {GATEWAY: GENERATED_GATEWAY_TOKEN}
+
+
+def hook_jobs(docs: list[dict]) -> dict[str, dict]:
+ return {doc["metadata"]["name"]: doc for doc in docs if doc["kind"] == "Job"}
+
+
+def test_enforced_worker_auth_adds_a_release_test_of_every_api_lane(tmp_path: Path) -> None:
+ pools = {
+ "l4": {"enabled": True},
+ "cpu": {"enabled": True, "bundles": {"candle": {"engine": "candle", "minReplicas": 0, "maxReplicas": 1}}},
+ }
+ docs = rendered_documents(tmp_path, {"workers": {"auth": {"enabled": True}, "pools": pools}})
+ job = hook_jobs(docs)[WORKER_AUTH_TEST_JOB]
+ assert job["metadata"]["annotations"]["helm.sh/hook"] == "post-install,post-upgrade"
+ (container,) = job["spec"]["template"]["spec"]["containers"]
+ script = container["args"][0]
+ assert 'LANES="sie-sie-cluster-worker-cpu-default sie-sie-cluster-worker-l4-default"' in script
+ assert "candle" not in script
+ assert "http://$host:$PORT/v1/models" in script
+ assert "401)" in script
+ assert "exit 1" in script
+ (role,) = [
+ doc for doc in docs if doc["kind"] == "Role" and doc["metadata"]["name"] == "sie-sie-cluster-worker-auth-test"
+ ]
+ assert role["rules"] == [
+ {
+ "apiGroups": ["apps"],
+ "resources": ["statefulsets"],
+ "resourceNames": ["sie-sie-cluster-worker-cpu-default", "sie-sie-cluster-worker-l4-default"],
+ "verbs": ["get"],
+ },
+ {"apiGroups": [""], "resources": ["pods"], "verbs": ["list"]},
+ ]
+
+
+def test_the_worker_auth_test_job_is_kept_and_ends_well_before_its_deadline(tmp_path: Path) -> None:
+ docs = rendered_documents(tmp_path, {"workers": {"auth": {"enabled": True}, **L4_POOL["workers"]}})
+ job = hook_jobs(docs)[WORKER_AUTH_TEST_JOB]
+ assert job["metadata"]["annotations"]["helm.sh/hook-delete-policy"] == "before-hook-creation"
+ assert job["spec"]["ttlSecondsAfterFinished"] >= 3600
+ (wait,) = re.findall(
+ r"DEADLINE=\$\(\( \$\(date \+%s\) \+ (\d+) \)\)", job["spec"]["template"]["spec"]["containers"][0]["args"][0]
+ )
+ assert job["spec"]["activeDeadlineSeconds"] - int(wait) >= 120
+
+
+ "workers",
+ [L4_POOL["workers"], {"auth": {"enabled": True, "allowUnauthenticated": True}, **L4_POOL["workers"]}],
+)
+def test_there_is_no_worker_auth_test_while_workers_do_not_require_the_token(tmp_path: Path, workers: dict) -> None:
+ assert WORKER_AUTH_TEST_JOB not in hook_jobs(rendered_documents(tmp_path, {"workers": workers}))
+
+
+SERVER_SOURCES = ROOT / "packages" / "sie_server" / "src"
+GATEWAY_SOURCES = ROOT / "packages" / "sie_gateway" / "src"
+
+
+def source_text(root: Path, suffix: str) -> str:
+ return "\n".join(path.read_text(encoding="utf-8") for path in sorted(root.rglob(f"*{suffix}")))
+
+
+def test_the_worker_auth_variables_the_chart_renders_are_read_by_the_images(tmp_path: Path) -> None:
+ docs = rendered_documents(tmp_path, {"workers": {"auth": {"enabled": True}, **L4_POOL["workers"]}})
+ worker_names = set(container_env(docs, "sie-sie-cluster-worker-l4-default", "worker")) & {
+ "SIE_AUTH_MODE",
+ "SIE_AUTH_TOKEN",
+ }
+ gateway_names = set(container_env(docs, "sie-sie-cluster-gateway", "gateway")) & {"SIE_WORKER_AUTH_TOKEN"}
+ assert worker_names == {"SIE_AUTH_MODE", "SIE_AUTH_TOKEN"}
+ assert gateway_names == {"SIE_WORKER_AUTH_TOKEN"}
+ server = source_text(SERVER_SOURCES, ".py")
+ gateway = source_text(GATEWAY_SOURCES, ".rs")
+ for name in sorted(worker_names):
+ assert f'"{name}"' in server, f"sie-server does not read {name}"
+ for name in sorted(gateway_names):
+ assert f'"{name}"' in gateway, f"sie-gateway does not read {name}"
+
+
+AUTH_TEST_POD_LABELS = {
+ "app.kubernetes.io/name": "sie-health-test",
+ "app.kubernetes.io/component": "worker-auth",
+ "app.kubernetes.io/instance": "sie",
+}
+
+
+def ingress_peers(docs: list[dict], policy_name: str) -> list[dict]:
+ (policy,) = [doc for doc in docs if doc["kind"] == "NetworkPolicy" and doc["metadata"]["name"] == policy_name]
+ (rule,) = policy["spec"]["ingress"]
+ return [peer["podSelector"]["matchLabels"] for peer in rule["from"]]
+
+
+ ("auth", "admitted"),
+ [({"enabled": True}, True), ({"enabled": True, "allowUnauthenticated": True}, False), ({}, False)],
+)
+def test_worker_policies_admit_the_auth_test_only_while_workers_require_the_token(
+ tmp_path: Path, auth: dict, admitted: bool
+) -> None:
+ values = remote_pool_values()
+ values["workers"].update({"auth": auth, "networkPolicy": {"enabled": True}})
+ values["workers"]["pools"]["l4"] = {"enabled": True}
+ docs = rendered_documents(tmp_path, values)
+ for policy in ("sie-sie-cluster-worker", "sie-sie-cluster-worker-remote"):
+ assert (AUTH_TEST_POD_LABELS in ingress_peers(docs, policy)) is admitted, policy
+ if admitted:
+ pod_labels = hook_jobs(docs)[WORKER_AUTH_TEST_JOB]["spec"]["template"]["metadata"]["labels"]
+ assert pod_labels == AUTH_TEST_POD_LABELS
+
+
+def test_the_worker_auth_test_fails_closed_and_reports_what_it_checked(tmp_path: Path) -> None:
+ docs = rendered_documents(tmp_path, {"workers": {"auth": {"enabled": True}, **L4_POOL["workers"]}})
+ script = hook_jobs(docs)[WORKER_AUTH_TEST_JOB]["spec"]["template"]["spec"]["containers"][0]["args"][0]
+ assert 'echo "FAILED: StatefulSet $lane not found."' in script
+ assert 'echo "FAILED: $lane has ready workers that did not answer from this pod."' in script
+ assert 'echo "WARNING: no worker was checked. Every lane was scaled to zero or still starting."' in script
+ assert '000|"")' in script
+
+
+WORKER_AUTH_KUBECTL = """
+import json, os, sys
+
+args = sys.argv[1:]
+with open(os.path.join(os.environ["STUB_DIR"], "kubectl.log"), "a") as log:
+ log.write(" ".join(args) + "\\n")
+output = args[args.index("-o") + 1] if "-o" in args else ""
+if args[:2] == ["get", "statefulset"]:
+ if os.environ["STUB_STATEFULSET"] != "present":
+ sys.exit(1)
+ answers = {
+ "jsonpath={.spec.replicas}": os.environ["STUB_REPLICAS"],
+ "jsonpath={.status.updateRevision}": "rev-2",
+ }
+ if output not in answers:
+ sys.exit(2)
+ print(answers[output], end="")
+elif args[:2] == ["get", "pods"] and output == "json" and "-l" in args:
+ if os.environ.get("STUB_PODS_FAIL"):
+ sys.exit(1)
+ key, _, value = args[args.index("-l") + 1].partition("=")
+ items = json.loads(os.environ["STUB_PODS"])["items"]
+ print(json.dumps({"items": [pod for pod in items if pod["metadata"].get("labels", {}).get(key) == value]}))
+else:
+ sys.exit(2)
+"""
+WORKER_AUTH_CURL = """
+import json, os, sys
+
+host = sys.argv[-1].removeprefix("http://").removesuffix("/v1/models").rpartition(":")[0]
+with open(os.path.join(os.environ["STUB_DIR"], "curl.log"), "a") as log:
+ log.write(host + "\\n")
+print(json.loads(os.environ["STUB_HTTP_CODES"]).get(host, os.environ["STUB_HTTP_CODE"]), end="")
+"""
+WORKER_AUTH_SHELL_STUBS = {
+ "date": """#!/bin/sh
+count=$(cat "$STUB_DIR/date-calls" 2>/dev/null || echo 0)
+echo $((count + 1)) > "$STUB_DIR/date-calls"
+if [ "$count" -eq 0 ]; then echo 0; else echo 100000; fi
+""",
+ "sleep": '#!/bin/sh\necho "$@" >> "$STUB_DIR/sleep.log"\n',
+}
+
+
+def worker_pod(ip: str, revision: str = "rev-2", ready: bool = True, terminating: bool = False) -> dict:
+ metadata: dict = {"labels": {"controller-revision-hash": revision}}
+ if terminating:
+ metadata["deletionTimestamp"] = "2026-01-01T00:00:00Z"
+ return {
+ "metadata": metadata,
+ "status": {"podIP": ip, "conditions": [{"type": "Ready", "status": "True" if ready else "False"}]},
+ }
+
+
+READY_POD = {"items": [worker_pod("10.0.0.7")]}
+MIXED_PODS = {
+ "items": [
+ worker_pod("10.0.0.1"),
+ worker_pod("10.0.0.2", ready=False),
+ worker_pod("10.0.0.3", terminating=True),
+ worker_pod("10.0.0.4", revision="rev-1"),
+ worker_pod("fd00::5"),
+ ]
+}
+MIXED_POD_CODES = {"10.0.0.1": "401", "10.0.0.2": "200", "10.0.0.3": "200", "10.0.0.4": "200", "[fd00::5]": "401"}
+
+
+def pipefail_shell() -> str:
+ """A POSIX shell that supports pipefail, as the hook image's BusyBox ash does."""
+ for shell in ("/bin/sh", shutil.which("bash") or "/bin/bash"):
+ if subprocess.run([shell, "-c", "set -o pipefail"], capture_output=True, check=False).returncode == 0:
+ return shell
+ pytest.fail("no POSIX shell with pipefail support")
+
+
+def worker_auth_test_script(tmp_path: Path) -> str:
+ docs = rendered_documents(tmp_path, {"workers": {"auth": {"enabled": True}, **L4_POOL["workers"]}})
+ return hook_jobs(docs)[WORKER_AUTH_TEST_JOB]["spec"]["template"]["spec"]["containers"][0]["args"][0]
+
+
+def run_worker_auth_test(
+ tmp_path: Path,
+ statefulset: str,
+ pods: dict,
+ http_code: str,
+ *,
+ replicas: str = "1",
+ http_codes: dict | None = None,
+ pods_fail: bool = False,
+) -> subprocess.CompletedProcess:
+ script = worker_auth_test_script(tmp_path)
+ stubs = tmp_path / "stubs"
+ stubs.mkdir()
+ for name, body in {
+ "kubectl": f"#!{sys.executable}\n{WORKER_AUTH_KUBECTL}",
+ "curl": f"#!{sys.executable}\n{WORKER_AUTH_CURL}",
+ **WORKER_AUTH_SHELL_STUBS,
+ }.items():
+ (stubs / name).write_text(body, encoding="utf-8")
+ (stubs / name).chmod(0o755)
+ env = {
+ "PATH": f"{stubs}:{os.environ['PATH']}",
+ "STUB_DIR": str(stubs),
+ "STUB_STATEFULSET": statefulset,
+ "STUB_REPLICAS": replicas,
+ "STUB_PODS": json.dumps(pods),
+ "STUB_HTTP_CODE": http_code,
+ "STUB_HTTP_CODES": json.dumps(http_codes or {}),
+ **({"STUB_PODS_FAIL": "1"} if pods_fail else {}),
+ }
+ script = script.replace("KUBECONFIG=/tmp/sie-in-cluster-kubeconfig", f"KUBECONFIG={tmp_path}/kubeconfig")
+ return subprocess.run(
+ [pipefail_shell(), "-c", script], env=env, capture_output=True, text=True, check=False, timeout=60
+ )
+
+
+def stub_log(tmp_path: Path, name: str) -> list[str]:
+ path = tmp_path / "stubs" / f"{name}.log"
+ return path.read_text(encoding="utf-8").splitlines() if path.exists() else []
+
+
+ ("statefulset", "pods", "http_code", "exit_code", "message"),
+ [
+ ("present", READY_POD, "401", 0, "SUCCESS: 1 worker(s) refused a request without a token."),
+ ("present", READY_POD, "200", 1, "answered GET /v1/models without a token (HTTP 200)"),
+ ("present", READY_POD, "404", 1, "answered GET /v1/models without a token (HTTP 404)"),
+ ("present", READY_POD, "000", 1, "has ready workers that did not answer from this pod"),
+ ("missing", READY_POD, "401", 1, "StatefulSet sie-sie-cluster-worker-l4-default not found"),
+ ("present", {"items": []}, "401", 0, "WARNING: no worker was checked."),
+ ],
+)
+def test_the_worker_auth_test_script_decides_on_what_it_observes(
+ tmp_path: Path, statefulset: str, pods: dict, http_code: str, exit_code: int, message: str
+) -> None:
+ result = run_worker_auth_test(tmp_path, statefulset, pods, http_code)
+ assert result.returncode == exit_code, result.stdout + result.stderr
+ assert message in result.stdout
+
+
+def test_the_worker_auth_test_checks_only_ready_workers_of_the_current_revision(tmp_path: Path) -> None:
+ result = run_worker_auth_test(tmp_path, "present", MIXED_PODS, "000", http_codes=MIXED_POD_CODES)
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "SUCCESS: 2 worker(s) refused a request without a token." in result.stdout
+ assert sorted(stub_log(tmp_path, "curl")) == ["10.0.0.1", "[fd00::5]"]
+ assert "get pods -l controller-revision-hash=rev-2 -o json" in stub_log(tmp_path, "kubectl")
+
+
+def test_the_worker_auth_test_skips_a_lane_scaled_to_zero_at_once(tmp_path: Path) -> None:
+ result = run_worker_auth_test(tmp_path, "present", READY_POD, "200", replicas="0")
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "SKIPPED: sie-sie-cluster-worker-l4-default is scaled to zero." in result.stdout
+ assert "WARNING: no worker was checked." in result.stdout
+ assert not [call for call in stub_log(tmp_path, "kubectl") if call.startswith("get pods")]
+ assert stub_log(tmp_path, "sleep") == []
+ assert stub_log(tmp_path, "curl") == []
+
+
+def test_the_worker_auth_test_fails_when_it_cannot_list_the_pods(tmp_path: Path) -> None:
+ result = run_worker_auth_test(tmp_path, "present", READY_POD, "401", pods_fail=True)
+ assert result.returncode == 1, result.stdout + result.stderr
+ assert "FAILED: cannot list the pods of sie-sie-cluster-worker-l4-default." in result.stdout
+ assert "WARNING" not in result.stdout
+
+
[email protected]("name", ["SIE_AUTH_MODE", "SIE_AUTH_TOKEN", "SIE_AUTH_TOKENS"])
+def test_worker_auth_variables_are_reserved_for_bundles_in_the_upgrade_step(tmp_path: Path, name: str) -> None:
+ bundle = {"default": {"extraEnv": [{"name": name, "value": "override"}]}}
+ workers = {
+ "auth": {"enabled": True, "allowUnauthenticated": True},
+ "pools": {"l4": {"enabled": True, "bundles": bundle}},
+ }
+ error = render_error(tmp_path, {"workers": workers})
+ assert f"workers.pools.l4.bundles.default.extraEnv must not override chart-owned variable {name}" in error
+
+
+def chart_app_version() -> str:
+ return yaml.safe_load((helm.CHART_DIR / "Chart.yaml").read_text(encoding="utf-8"))["appVersion"]
+
+
+def older_version(version: str) -> str:
+ major, minor, patch = (int(part) for part in version.lstrip("v").split("."))
+ return f"v{major}.{minor}.{patch - 1}" if patch else f"v{major}.{minor - 1}.0" if minor else f"v{major - 1}.0.0"
+
+
+def test_worker_auth_refuses_a_worker_image_tag_older_than_the_chart(tmp_path: Path) -> None:
+ tag = older_version(chart_app_version())
+ workers = {"auth": {"enabled": True}, "common": {"image": {"tag": tag}}, **L4_POOL["workers"]}
+ error = render_error(tmp_path, {"workers": workers})
+ assert f"workers.common.image.tag={tag} is older" in error
+ workers["auth"]["allowUnauthenticated"] = True
+ assert f"workers.common.image.tag={tag} is older" in render_error(tmp_path, {"workers": workers})
+
+
+ ("auth", "tag"),
+ [
+ ({"enabled": True}, None),
+ ({"enabled": True}, "same"),
+ ({"enabled": True}, "v99.0.0"),
+ ({"enabled": True}, "main"),
+ ({}, "older"),
+ ],
+)
+def test_worker_image_tags_that_enforce_or_cannot_be_compared_render(
+ tmp_path: Path, auth: dict, tag: str | None
+) -> None:
+ version = chart_app_version()
+ tags = {"same": version, "older": older_version(version)}
+ common = {"image": {"tag": tags.get(tag, tag)}} if tag else {}
+ rendered_documents(tmp_path, {"workers": {"auth": auth, "common": common, **L4_POOL["workers"]}})