Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(config)!: give gateways and worker sidecars a read-only sie-config token (#418)
Krisztian Gajdaref3eb69b3314
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 4e1257b26..7bbf3df90 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -10,8 +10,8 @@ helm install sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \--create-namespace```-With the defaults, the chart generates the sie-config admin token (see-[sie-config admin token](#sie-config-admin-token)) and installs without a+With the defaults, the chart generates the sie-config admin and read tokens+(see [sie-config tokens](#sie-config-tokens)) and installs without apayload store, so work items larger than 1MB fail until one is configured (see[Payload store](#payload-store)). All worker pools are disabled by default;enable the pools you need (see [Configuration](#configuration)).@@ -893,39 +893,70 @@ Run these once per cluster after the upgrade settles. LeftoverScaledObjects will keep trying to scale deleted StatefulSets and spamKEDA logs; leftover PDBs will block node drains.-## sie-config admin token+## sie-config tokens-sie-config serves the model catalog on `/v1/configs/*`, and one admin token-authorizes every read and write on that API. The gateway presents it to load-and refresh its catalog, worker sidecars present it to reconcile missed config-updates, and admin tooling presents it for writes. All three read it from the-same Secret.+sie-config serves the model catalog on `/v1/configs/*` and accepts two tokens+there:++| Token | sie-config variable | Authorizes | Held by |+| --- | --- | --- | --- |+| Admin | `SIE_ADMIN_TOKEN` | Every read and write | sie-config and the admin tooling that writes configs |+| Read | `SIE_CONFIG_READ_TOKEN` | Every read, including `GET /v1/configs/export`; never a write | sie-config, every gateway pod, and every worker sidecar |++The gateway presents the read token to load and refresh its catalog, and+worker sidecars present it to reconcile missed config updates. Both receive it+as `SIE_CONFIG_SERVICE_TOKEN`. The gateway always gets that variable, empty+when the chart runs no sie-config, so it never presents another credential in+its place. Neither receives the admin token, so a gateway or worker pod cannot+write to sie-config.++Every read-token holder can read every model config, through+`GET /v1/configs/models/{id}` and the export, including `adapter_options` such+as `loadtime.extra_env`. Never put secrets in model configs.++Each token is either generated by the chart or managed by the operator, chosen+per token:- **Generated (default).** With `config.auth.adminTokenSecretName` empty and`config.auth.generateAdminToken=true`, the chart creates the Secret`<fullname>-config-admin-token` (`sie-cluster-config-admin-token` for theQuick Start release) holding a random 64-character token under- `config.auth.adminTokenSecretKey` (`SIE_ADMIN_TOKEN`). An absent- `generateAdminToken` key, as after `helm upgrade --reuse-values` from an- older release, counts as `true`. Upgrades read the existing Secret and keep- its token; the render fails if the Secret has no value under that key or the- value is shorter than 32 characters. The- Secret carries `helm.sh/resource-policy: keep`, so `helm uninstall` leaves it- in place; delete it manually when it is no longer needed.-- **Operator-managed.** Set `config.auth.adminTokenSecretName` (and- `config.auth.adminTokenSecretKey` if the key differs) to an existing Secret.- The chart uses it unchanged and creates no Secret. Use this mode with- renderers that cannot read the cluster, such as `helm template` or GitOps- controllers (see [GitOps and `helm template`](#gitops-and-helm-template)).+ `config.auth.adminTokenSecretKey` (`SIE_ADMIN_TOKEN`). When sie-config has an+ admin token, `config.auth.readTokenSecretName` is empty, and+ `config.auth.generateReadToken=true`, it likewise creates+ `<fullname>-config-read-token` holding a separate token under+ `config.auth.readTokenSecretKey` (`SIE_CONFIG_READ_TOKEN`). An absent key, as+ after `helm upgrade --reuse-values` from an older release, takes its+ default. Upgrades read each existing Secret and keep its token; the render+ fails if the Secret has no value under the configured key or the value is+ shorter than 32 characters. Both Secrets carry+ `helm.sh/resource-policy: keep`, so `helm uninstall` leaves them in place;+ delete them manually when they are no longer needed.+- **Operator-managed.** Set `config.auth.adminTokenSecretName` or+ `config.auth.readTokenSecretName` (and the matching `...SecretKey` if the+ key differs) to an existing Secret. The chart uses it unchanged and creates+ no Secret for that token. Use this mode for both tokens with renderers that+ cannot read the cluster, such as `helm template` or GitOps controllers (see+ [GitOps and `helm template`](#gitops-and-helm-template)).++The render fails when `config.auth.readTokenSecretName` and its key point at+the admin token's Secret and key, since that would hand the admin token to+every gateway and worker sidecar. The two tokens may share a Secret under+different keys. The gateway and worker sidecar `extraEnv` lists cannot set+`SIE_ADMIN_TOKEN` or `SIE_CONFIG_SERVICE_TOKEN`; the settings above are the only+source.`config.auth.mode` is not read by any template and is kept only so existing-values files stay valid; the two settings above decide the token.+values files stay valid; the settings above decide the tokens.-Read the generated token for admin tooling:+Read the generated tokens, the admin token for admin tooling and the read+token for read-only tooling:```bashkubectl get secret -n sie sie-cluster-config-admin-token \-o jsonpath='{.data.SIE_ADMIN_TOKEN}' | base64 -d+kubectl get secret -n sie sie-cluster-config-read-token \+ -o jsonpath='{.data.SIE_CONFIG_READ_TOKEN}' | base64 -d````telemetry.deploymentEnv` is also sie-config's deployment environment@@ -936,7 +967,13 @@ writes open to anything that can reach the Service. With`config.auth.generateAdminToken=false` and `config.auth.adminTokenSecretName`empty, the chart therefore renders only when `telemetry.deploymentEnv` is`staging`, `development`, or `ci`, and fails the render for production and-for any unrecognized value.+for any unrecognized value. In that case the chart generates no read token,+and the gateway and worker sidecars send none.++With an admin token, sie-config also needs a read token:+`config.auth.generateReadToken=false` with `config.auth.readTokenSecretName`+empty fails the render, because the gateway and worker sidecars would have no+credential for the catalog.The gateway reports `503` on `/readyz` until it has loaded its first completecatalog from sie-config, so a missing or mismatched token keeps new gateway@@ -947,65 +984,68 @@ sie-config and, when sie-config requires a token, authenticated. It acceptswhatever complete catalog sie-config serves and does not validate thecatalog's contents.-> **Upgrade note:** upgrading an install without-> `config.auth.adminTokenSecretName` creates the Secret and adds-> `SIE_ADMIN_TOKEN` to sie-config, the gateway, and the worker sidecars, so-> those pods roll. sie-config then requires the token for every `/v1/configs`-> request, including on installs with a non-production-> `telemetry.deploymentEnv` that previously served the API without one. Update-> admin tooling to send the token. To keep an unauthenticated sie-config-> instead, set `config.auth.generateAdminToken=false`; the chart renders that-> only when `telemetry.deploymentEnv` is `staging`, `development`, or `ci`. An-> install that uses another name (for example `dev`, `test`, `qa`, or-> `preprod`) fails the render with that setting and must either keep the token-> or switch to one of those names. Because the auth posture is keyed off the-> telemetry value, switching the name also changes the anonymous-telemetry-> environment tag and, unless `observability.otel.resource.deploymentEnvironment`-> is set explicitly, the OTel `deployment.environment` label on dashboards.--### Who holds the token--The token is available to sie-config, every gateway pod, every worker sidecar,-and anyone who can read Secrets in the release namespace. Limit Secret read-access in that namespace accordingly.--With `gateway.auth.mode` set to `token` or `static`, the gateway also accepts-this token on its admin routes: `POST`, `PUT`, and `DELETE` requests under-`/v1/pools`, `/v1/admin`, and `/v1/configs`, which include pool create, renew,-and delete and `POST /v1/configs/resolve`. Before the chart generated a token,-those routes answered `403` (`Admin token not configured`) unless an operator-set `config.auth.adminTokenSecretName`; now the generated token unlocks them.--### Rotating the token--sie-config accepts one admin token at a time, and every component reads the-token at container start. To rotate it, update the Secret, restart sie-config-first, and then restart the gateway and the worker StatefulSets. Until a-gateway or worker sidecar restarts, sie-config answers its old token with-`403`: a running gateway keeps serving its current catalog and still receives-live NATS config deltas, but its epoch poll and export catch-up fail; a new-gateway pod stays at `503`; and worker sidecars cannot reconcile missed updates.--Helm stores the rendered Secret, including the token, in every release-revision. A `helm rollback` to a revision from before a rotation restores the-old token, so rotate again after such a rollback. Anyone who can read Secrets-in the release namespace can also read earlier tokens from the release-history.+### Gateway admin token++With `gateway.auth.mode` set to `token` or `static`, the gateway gates its own+admin routes: `POST`, `PUT`, and `DELETE` requests under `/v1/pools`,+`/v1/admin`, and `/v1/configs`, which include pool create, renew, and delete+and `POST /v1/configs/resolve`. They accept the token in the Secret named by+`gateway.auth.adminTokenSecretName` (key `gateway.auth.adminTokenSecretKey`,+default `SIE_ADMIN_TOKEN`), which the chart passes to the gateway as+`SIE_ADMIN_TOKEN`. When it is empty, those requests get `403` (`Admin token not+configured`). The chart does not generate this token, and it must be separate+from the sie-config tokens: the render fails when it names the Secret and key+of the sie-config admin token, which would give every gateway pod catalog+write access, or of the read token, which every worker sidecar holds.++### Who holds which token++- **sie-config admin token:** sie-config and the admin tooling you give it to.+- **sie-config read token:** sie-config, every gateway pod, and every worker+ sidecar. It can read the whole catalog, including every model config, but+ cannot write.+- **Gateway admin token (when set):** every gateway pod and the tooling that+ manages pools.++Anyone who can read Secrets in the release namespace can read all of them.+Limit Secret read access in that namespace accordingly.++### Rotating the tokens++sie-config accepts one admin token and one read token at a time, and every+component reads its token at container start.++- **Admin token:** update its Secret and restart sie-config, then give admin+ tooling the new token. The gateway and the workers do not hold it and keep+ working.+- **Read token:** update its Secret, restart sie-config first, and then restart+ the gateway and the worker StatefulSets. Until a gateway or worker sidecar+ restarts, sie-config answers its old token with `403`: a running gateway+ keeps serving its current catalog and still receives live NATS config+ deltas, but its epoch poll and export catch-up fail; a new gateway pod stays+ at `503`; and worker sidecars cannot reconcile missed updates.++Helm stores the rendered Secrets, including the generated tokens, in every+release revision. A `helm rollback` to a revision from before a rotation+restores the old token, so rotate again after such a rollback. Anyone who can+read Secrets in the release namespace can also read earlier tokens from the+release history.### GitOps and `helm template``helm template`, and GitOps controllers that render the chart the same way(for example Argo CD), cannot read the cluster. The chart's lookup of the-existing Secret finds nothing, so every render carries a new random token.-Applying each render replaces the token in the Secret, and pods pick up+existing Secrets finds nothing, so every render carries new random tokens.+Applying each render replaces the tokens in the Secrets, and pods pick updifferent tokens as they restart: worker sidecars get `403` when theyreconcile, new gateway pods stay at `503`, and every component fails oncesie-config restarts with a token the others do not hold.-- **Recommended:** create the Secret outside the chart, for example with an- external secret manager, and set `config.auth.adminTokenSecretName`.-- **Argo CD with a generated token:** have Argo CD keep the live token by- ignoring the Secret's data both when diffing and when syncing:+- **Recommended:** create both Secrets outside the chart, for example with an+ external secret manager, and set `config.auth.adminTokenSecretName` and+ `config.auth.readTokenSecretName`.+- **Argo CD with generated tokens:** have Argo CD keep the live tokens by+ ignoring the Secrets' data both when diffing and when syncing:```yamlspec:@@ -1015,18 +1055,66 @@ sie-config restarts with a token the others do not hold.namespace: siejsonPointers:- /data+ - kind: Secret+ name: sie-cluster-config-read-token+ namespace: sie+ jsonPointers:+ - /datasyncPolicy:syncOptions:- RespectIgnoreDifferences=true````RespectIgnoreDifferences=true` makes Argo CD apply `ignoreDifferences`- during sync, not only in the diff. It takes effect only once the Secret- exists, so the first sync creates the Secret with the token from that render- and later syncs keep it.--Do not commit `helm template` output to a repository: the rendered Secret-contains the generated token.+ during sync, not only in the diff. It takes effect only once a Secret exists,+ so the first sync creates each Secret with the token from that render and+ later syncs keep it.++Do not commit `helm template` output to a repository: the rendered Secrets+contain the generated tokens.++### Upgrade notes++> **Installs without `config.auth.adminTokenSecretName`:** the upgrade creates+> the admin-token Secret and adds `SIE_ADMIN_TOKEN` to sie-config, so it rolls.+> sie-config then requires a token for every `/v1/configs` request, including+> on installs with a non-production `telemetry.deploymentEnv` that previously+> served the API without one. Update admin tooling to send the admin token. To+> keep an unauthenticated sie-config instead, set+> `config.auth.generateAdminToken=false`; the chart renders that only when+> `telemetry.deploymentEnv` is `staging`, `development`, or `ci`. An install+> that uses another name (for example `dev`, `test`, `qa`, or `preprod`) fails+> the render with that setting and must either keep the token or switch to one+> of those names. Because the auth posture is keyed off the telemetry value,+> switching the name also changes the anonymous-telemetry environment tag and,+> unless `observability.otel.resource.deploymentEnvironment` is set explicitly,+> the OTel `deployment.environment` label on dashboards.++> **Separate read token:** the upgrade creates the read-token Secret (unless+> `config.auth.readTokenSecretName` is set), adds `SIE_CONFIG_READ_TOKEN` to+> sie-config, and gives the gateway and worker sidecars `SIE_CONFIG_SERVICE_TOKEN`+> instead of `SIE_ADMIN_TOKEN`, so those pods roll. The admin-token Secret is+> unchanged.+>+> - Run the sie-config, gateway, and worker sidecar images of this chart's+> release together. An older sie-config rejects the read token, so new+> gateway pods stay at `503` and worker sidecars cannot reconcile; older+> gateway and sidecar images present only `SIE_ADMIN_TOKEN`, which they no+> longer receive. During an ordinary rolling upgrade, new gateway pods that+> start before the new sie-config is ready stay at `503` until it is, while+> the old pods keep serving.+> - The gateway no longer accepts the sie-config admin token on its admin+> routes. With `gateway.auth.mode` set to `token` or `static`, set+> `gateway.auth.adminTokenSecretName` before upgrading if you use those+> routes; until then they answer `403`.+> - GitOps installs that set `config.auth.adminTokenSecretName` now get a+> generated read token, with the `helm template` behavior described above.+> Set `config.auth.readTokenSecretName` to an externally managed Secret+> before upgrading.+> - Gateways and worker sidecars run outside this chart keep working with only+> `SIE_ADMIN_TOKEN`: when `SIE_CONFIG_SERVICE_TOKEN` is unset they fall back+> to it and log a deprecation warning. Move them to `SIE_CONFIG_SERVICE_TOKEN`+> with a read token.## Ingress@@ -1364,7 +1452,7 @@ telemetry:`telemetry.deploymentEnv` is not only a dashboard tag: it is also passed tosie-config as `SIE_DEPLOYMENT_ENV` and decides whether sie-config may serve its-API without an admin token. See [sie-config admin token](#sie-config-admin-token).+API without an admin token. See [sie-config tokens](#sie-config-tokens).## Observabilitydiff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txtindex c4d7678cf..ac7b6cdc0 100644--- a/deploy/helm/sie-cluster/templates/NOTES.txt+++ b/deploy/helm/sie-cluster/templates/NOTES.txt@@ -11,6 +11,9 @@ Gateway: http://{{ include "sie-cluster.gateway.serviceName" . }}.{{ include "si{{- if and .Values.config.enabled (include "sie-cluster.config.generatesAdminToken" .) }}sie-config admin token: kubectl get secret -n {{ include "sie-cluster.namespace" . }} {{ include "sie-cluster.config.generatedAdminTokenSecretName" . }} -o jsonpath='{.data.{{ include "sie-cluster.config.adminTokenSecretKey" . | replace "." "\\." }}}' | base64 -d{{- end }}+{{- 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 $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.tplindex 3579408c1..f181e394e 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -330,19 +330,20 @@ render when it is empty or null."true" when the chart generates the admin-token Secret: noconfig.auth.adminTokenSecretName, and config.auth.generateAdminToken is notfalse. An absent key counts as true, so `helm upgrade --reuse-values` from a-release that predates the key keeps the default.+release that predates the key keeps the default. An empty value also counts as+true.*/}}{{- define "sie-cluster.config.generatesAdminToken" -}}{{- $auth := .Values.config.auth | default dict -}}-{{- if and (not $auth.adminTokenSecretName) (dig "generateAdminToken" true $auth) -}}+{{- if and (not $auth.adminTokenSecretName) (ne (dig "generateAdminToken" true $auth | toString | trim | lower) "false") -}}true{{- end -}}{{- end }}{{/*-Secret holding the sie-config admin token that sie-config, the gateway, and-worker sidecars share: config.auth.adminTokenSecretName when set, otherwise the-chart-generated Secret, otherwise empty (no token).+Secret holding the sie-config admin (write) token, which only sie-config reads:+config.auth.adminTokenSecretName when set, otherwise the chart-generated+Secret, otherwise empty (no token).*/}}{{- define "sie-cluster.config.adminTokenSecretName" -}}{{- if .Values.config.auth.adminTokenSecretName -}}@@ -353,32 +354,177 @@ chart-generated Secret, otherwise empty (no token).{{- end }}{{/*-Fail when an existing admin-token Secret has no value under the configured key,-or a value shorter than 32 characters, instead of replacing the token that-running pods hold. Args (dict): name (Secret), key (data key), data (base64-value, empty when the key is missing).+Data key of the read-token Secret (config.auth.readTokenSecretKey). An absent+key, as after `helm upgrade --reuse-values` from a release that predates it,+takes the default; an empty value fails the render.*/}}-{{- define "sie-cluster.config.validateReusedAdminToken" -}}+{{- define "sie-cluster.config.readTokenSecretKey" -}}+{{- $key := dig "readTokenSecretKey" "SIE_CONFIG_READ_TOKEN" (.Values.config.auth | default dict) | default "" | toString | trim -}}+{{- if not $key -}}+{{- fail "config.auth.readTokenSecretKey is empty. Set it to the Secret key that holds the sie-config read token (the chart default is SIE_CONFIG_READ_TOKEN)." -}}+{{- end -}}+{{- $key -}}+{{- end }}++{{- define "sie-cluster.config.generatedReadTokenSecretName" -}}+{{- printf "%s-read-token" (include "sie-cluster.config.serviceName" .) -}}+{{- end }}++{{/*+"true" when the chart generates the read-token Secret: sie-config has an admin+token, config.auth.readTokenSecretName is empty, and+config.auth.generateReadToken is not false. Absent keys take their defaults,+so `helm upgrade --reuse-values` from a release that predates them generates+the Secret. An empty generateReadToken also counts as true.+*/}}+{{- define "sie-cluster.config.generatesReadToken" -}}+{{- $auth := .Values.config.auth | default dict -}}+{{- if and (include "sie-cluster.config.adminTokenSecretName" .) (not (dig "readTokenSecretName" "" $auth)) (ne (dig "generateReadToken" true $auth | toString | trim | lower) "false") -}}+true+{{- end -}}+{{- end }}++{{/*+Secret holding the read-scoped sie-config token that sie-config accepts on+reads and the gateway and worker sidecars present: config.auth.readTokenSecretName+when set, otherwise the chart-generated Secret, otherwise empty (no token).+*/}}+{{- define "sie-cluster.config.readTokenSecretName" -}}+{{- $name := dig "readTokenSecretName" "" (.Values.config.auth | default dict) -}}+{{- if $name -}}+{{- $name -}}+{{- else if include "sie-cluster.config.generatesReadToken" . -}}+{{- include "sie-cluster.config.generatedReadTokenSecretName" . -}}+{{- end -}}+{{- end }}++{{/*+Env entry SIE_CONFIG_SERVICE_TOKEN for a sie-config consumer (the gateway or a+worker sidecar): the read token, or an empty value when the chart runs no+sie-config or sie-config has no read token, so the consumer never falls back to+presenting SIE_ADMIN_TOKEN.+*/}}+{{- define "sie-cluster.config.serviceTokenEnv" -}}+{{- $secret := "" -}}+{{- if .Values.config.enabled -}}+{{- $secret = include "sie-cluster.config.readTokenSecretName" . -}}+{{- end -}}+- name: SIE_CONFIG_SERVICE_TOKEN+{{- if $secret }}+ valueFrom:+ secretKeyRef:+ name: {{ $secret }}+ key: {{ include "sie-cluster.config.readTokenSecretKey" . }}+{{- else }}+ value: ""+{{- end }}+{{- end }}++{{/*+Data key of the gateway's inbound admin-token Secret+(gateway.auth.adminTokenSecretKey), with the same absent-key default and+empty-value failure as the sie-config keys.+*/}}+{{- define "sie-cluster.gateway.adminTokenSecretKey" -}}+{{- $key := dig "adminTokenSecretKey" "SIE_ADMIN_TOKEN" (.Values.gateway.auth | default dict) | default "" | toString | trim -}}+{{- if not $key -}}+{{- fail "gateway.auth.adminTokenSecretKey is empty. Set it to the Secret key that holds the gateway admin token (the chart default is SIE_ADMIN_TOKEN)." -}}+{{- end -}}+{{- $key -}}+{{- 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).+*/}}+{{- define "sie-cluster.config.generatedTokenSecret" -}}+{{- $token := randAlphaNum 64 | b64enc -}}+{{- with lookup "v1" "Secret" (include "sie-cluster.namespace" $.root) $.name -}}+{{- $existing := index (.data | default dict) $.key | default "" -}}+{{- include "sie-cluster.config.validateReusedToken" (dict "name" $.name "key" $.key "data" $existing "keySetting" $.keySetting "nameSetting" $.nameSetting) -}}+{{- $token = $existing -}}+{{- end }}+apiVersion: v1+kind: Secret+metadata:+ name: {{ .name }}+ namespace: {{ include "sie-cluster.namespace" .root }}+ labels:+ {{- include "sie-cluster.config.labels" .root | nindent 4 }}+ annotations:+ helm.sh/resource-policy: keep+type: Opaque+data:+ {{ .key | quote }}: {{ $token | quote }}+{{- end }}++{{/*+Fail when an existing chart-generated token Secret has no value under the+configured key, or a value shorter than 32 characters, instead of replacing the+token that running pods hold. Args (dict): name (Secret), key (data key), data+(base64 value, empty when the key is missing), keySetting and nameSetting (the+values paths for the Secret key and an operator-managed Secret).+*/}}+{{- define "sie-cluster.config.validateReusedToken" -}}{{- if not .data -}}-{{- fail (printf "Secret %s exists but has no %s key. If config.auth.adminTokenSecretKey was renamed, set it back to the key the Secret holds. If the Secret was created by hand, set config.auth.adminTokenSecretName to it so the chart uses it unchanged. Otherwise restore the key, or delete the Secret so the chart generates a new token, then restart sie-config, the gateway, and the workers." .name .key) -}}+{{- fail (printf "Secret %s exists but has no %s key. If %s was renamed, set it back to the key the Secret holds. If the Secret was created by hand, set %s to it so the chart uses it unchanged. Otherwise restore the key, or delete the Secret so the chart generates a new token, then restart sie-config, the gateway, and the workers." .name .key .keySetting .nameSetting) -}}{{- else if lt (len (b64dec .data)) 32 -}}{{- fail (printf "Secret %s holds a %s value shorter than 32 characters. Replace it with a random value of at least 32 characters, or delete the Secret so the chart generates a new token, then restart sie-config, the gateway, and the workers." .name .key) -}}{{- end -}}{{- end }}{{/*-Fail the render when sie-config would run without an admin token outside-staging, development, or ci. In production ("prod" or "production") it would-refuse every /v1/configs request, so the gateway and worker sidecars could never-load the model catalog; any other value would leave the API unauthenticated.+Fail the render when the sie-config tokens are not kept apart or sie-config+would run without an admin token outside staging, development, or ci:+- an admin token without a read token leaves the gateway and worker sidecars+ without a credential;+- a read token or gateway admin token that is the same Secret key as the+ sie-config admin token hands the write credential to every gateway or worker+ sidecar, and a gateway admin token that is the read token's Secret key lets+ every worker sidecar call the gateway admin routes;+- without an admin token, production ("prod" or "production") refuses every+ write (and every read without a read token), and any other value leaves the+ API unauthenticated.*/}}{{- define "sie-cluster.config.validateAuth" -}}-{{- if not (include "sie-cluster.config.adminTokenSecretName" .) -}}+{{- $admin := include "sie-cluster.config.adminTokenSecretName" . -}}+{{- $read := include "sie-cluster.config.readTokenSecretName" . -}}+{{- if and $admin (not $read) -}}+{{- fail "sie-config has an admin token but no read token (config.auth.generateReadToken=false and config.auth.readTokenSecretName is empty), so the gateway and worker sidecars would have no credential to load the model catalog. Set config.auth.readTokenSecretName to an existing Secret, or set config.auth.generateReadToken=true so the chart generates one." -}}+{{- end -}}+{{- $adminRef := "" -}}+{{- if $admin -}}+{{- $adminRef = printf "%s/%s" $admin (include "sie-cluster.config.adminTokenSecretKey" .) -}}+{{- end -}}+{{- $readRef := "" -}}+{{- if $read -}}+{{- $readRef = printf "%s/%s" $read (include "sie-cluster.config.readTokenSecretKey" .) -}}+{{- end -}}+{{- if and $adminRef (eq $readRef $adminRef) -}}+{{- fail (printf "config.auth.readTokenSecretName and readTokenSecretKey point at the sie-config admin token (%s), which would give every gateway and worker sidecar write access to the model catalog. Store the read token in a different Secret or key." $adminRef) -}}+{{- end -}}+{{- with dig "adminTokenSecretName" "" (.Values.gateway.auth | default dict) -}}+{{- $gatewayRef := printf "%s/%s" . (include "sie-cluster.gateway.adminTokenSecretKey" $) -}}+{{- if and $adminRef (eq $gatewayRef $adminRef) -}}+{{- fail (printf "gateway.auth.adminTokenSecretName and adminTokenSecretKey point at the sie-config admin token (%s), which would give every gateway pod write access to the model catalog. Create a separate Secret for the gateway admin token." $gatewayRef) -}}+{{- end -}}+{{- if and $readRef (eq $gatewayRef $readRef) -}}+{{- fail (printf "gateway.auth.adminTokenSecretName and adminTokenSecretKey point at the sie-config read token (%s), which every worker sidecar holds, so any worker sidecar could call the gateway admin routes. Create a separate Secret for the gateway admin token." $gatewayRef) -}}+{{- end -}}+{{- end -}}+{{- if not $admin -}}{{- $env := include "sie-cluster.config.deploymentEnv" . | trim | lower -}}-{{- if has $env (list "prod" "production") -}}-{{- fail (printf "sie-config would run with telemetry.deploymentEnv=%q and no admin token (config.auth.generateAdminToken=false and config.auth.adminTokenSecretName is empty), so it would refuse every /v1/configs request and the gateway could not load the model catalog. Set config.auth.adminTokenSecretName to an existing Secret, or set config.auth.generateAdminToken=true so the chart generates one." $env) -}}-{{- else if not (has $env (list "staging" "development" "ci")) -}}-{{- fail (printf "sie-config would run with telemetry.deploymentEnv=%q and no admin token (config.auth.generateAdminToken=false and config.auth.adminTokenSecretName is empty), so it would serve /v1/configs without authentication. Running without a token is supported only for telemetry.deploymentEnv staging, development, or ci. Otherwise set config.auth.adminTokenSecretName to an existing Secret, or set config.auth.generateAdminToken=true so the chart generates one." $env) -}}+{{- $production := has $env (list "prod" "production") -}}+{{- if or $production (not (has $env (list "staging" "development" "ci"))) -}}+{{- $effect := "serve /v1/configs without authentication" -}}+{{- if $read -}}+{{- $effect = "refuse every config write and serve only reads that present the read token" -}}+{{- else if $production -}}+{{- $effect = "refuse every /v1/configs request and the gateway could not load the model catalog" -}}+{{- end -}}+{{- fail (printf "sie-config would run with telemetry.deploymentEnv=%q and no admin token (config.auth.generateAdminToken=false and config.auth.adminTokenSecretName is empty), so it would %s. Running without an admin token is supported only for telemetry.deploymentEnv staging, development, or ci. Otherwise set config.auth.adminTokenSecretName to an existing Secret, or set config.auth.generateAdminToken=true so the chart generates one." $env $effect) -}}{{- end -}}{{- end -}}{{- end }}diff --git a/deploy/helm/sie-cluster/templates/config-admin-token-secret.yaml b/deploy/helm/sie-cluster/templates/config-admin-token-secret.yamlindex 856879047..91403f593 100644--- a/deploy/helm/sie-cluster/templates/config-admin-token-secret.yaml+++ b/deploy/helm/sie-cluster/templates/config-admin-token-secret.yaml@@ -1,22 +1,3 @@{{- if and .Values.config.enabled (include "sie-cluster.config.generatesAdminToken" .) }}-{{- $name := include "sie-cluster.config.generatedAdminTokenSecretName" . }}-{{- $key := include "sie-cluster.config.adminTokenSecretKey" . }}-{{- $token := randAlphaNum 64 | b64enc }}-{{- with lookup "v1" "Secret" (include "sie-cluster.namespace" .) $name }}-{{- $existing := index (.data | default dict) $key | default "" }}-{{- include "sie-cluster.config.validateReusedAdminToken" (dict "name" $name "key" $key "data" $existing) }}-{{- $token = $existing }}-{{- end }}-apiVersion: v1-kind: Secret-metadata:- name: {{ $name }}- namespace: {{ include "sie-cluster.namespace" . }}- labels:- {{- include "sie-cluster.config.labels" . | nindent 4 }}- annotations:- helm.sh/resource-policy: keep-type: Opaque-data:- {{ $key | quote }}: {{ $token | quote }}+{{- include "sie-cluster.config.generatedTokenSecret" (dict "root" . "name" (include "sie-cluster.config.generatedAdminTokenSecretName" .) "key" (include "sie-cluster.config.adminTokenSecretKey" .) "keySetting" "config.auth.adminTokenSecretKey" "nameSetting" "config.auth.adminTokenSecretName") }}{{- end }}diff --git a/deploy/helm/sie-cluster/templates/config-deployment.yaml b/deploy/helm/sie-cluster/templates/config-deployment.yamlindex 00c3a67ce..796aefa4d 100644--- a/deploy/helm/sie-cluster/templates/config-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/config-deployment.yaml@@ -100,6 +100,14 @@ spec:name: {{ . }}key: {{ include "sie-cluster.config.adminTokenSecretKey" $ }}{{- end }}+ {{- with include "sie-cluster.config.readTokenSecretName" . }}+ # Read-scoped token that the gateway and worker sidecars present.+ - name: SIE_CONFIG_READ_TOKEN+ valueFrom:+ secretKeyRef:+ name: {{ . }}+ key: {{ include "sie-cluster.config.readTokenSecretKey" $ }}+ {{- end }}{{- if .Values.nats.enabled }}- name: SIE_NATS_URLvalue: {{ .Values.nats.url | default (printf "nats://%s-nats:4222" .Release.Name) | quote }}diff --git a/deploy/helm/sie-cluster/templates/config-read-token-secret.yaml b/deploy/helm/sie-cluster/templates/config-read-token-secret.yamlnew file mode 100644index 000000000..eb139a9fa--- /dev/null+++ b/deploy/helm/sie-cluster/templates/config-read-token-secret.yaml@@ -0,0 +1,3 @@+{{- if and .Values.config.enabled (include "sie-cluster.config.generatesReadToken" .) }}+{{- include "sie-cluster.config.generatedTokenSecret" (dict "root" . "name" (include "sie-cluster.config.generatedReadTokenSecretName" .) "key" (include "sie-cluster.config.readTokenSecretKey" .) "keySetting" "config.auth.readTokenSecretKey" "nameSetting" "config.auth.readTokenSecretName") }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex 6a5006d05..0b401eca0 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -17,7 +17,11 @@work streams and whoever gets there first wins, so the chart renders onevalue onto both. An extraEnv override would move only the gateway andsilently reintroduce exactly the divergence the render guards below- exist to prevent. Fail the render instead. */}}+ exist to prevent. Fail the render instead.++ SIE_ADMIN_TOKEN and SIE_CONFIG_SERVICE_TOKEN come only from+ gateway.auth.adminTokenSecretName and config.auth, where the render+ guards keep the gateway admin token and the sie-config tokens apart. */}}{{- $reservedGatewayEnv := concat(include "sie-cluster.otel.reservedEnvNames" . | fromJsonArray)(list@@ -27,6 +31,8 @@"SIE_GATEWAY_HEALTH_MODE""SIE_GATEWAY_MACHINE_PROFILES""SIE_GATEWAY_STATIC_QUEUE_POOLS"+ "SIE_ADMIN_TOKEN"+ "SIE_CONFIG_SERVICE_TOKEN""SIE_STREAM_MAX_AGE_S""SIE_STREAM_REPLICAS""SIE_STREAM_STORAGE") -}}@@ -260,6 +266,15 @@ spec:name: {{ .Values.gateway.auth.tokenSecretName }}key: {{ .Values.gateway.auth.tokenSecretKey }}{{- end }}+ {{- with dig "adminTokenSecretName" "" (.Values.gateway.auth | default dict) }}+ # Inbound admin token for POST, PUT, and DELETE under /v1/pools,+ # /v1/admin, and /v1/configs. Separate from the sie-config tokens.+ - name: SIE_ADMIN_TOKEN+ valueFrom:+ secretKeyRef:+ name: {{ . }}+ key: {{ include "sie-cluster.gateway.adminTokenSecretKey" $ }}+ {{- end }}{{- if .Values.nats.enabled }}- name: SIE_NATS_URLvalue: {{ .Values.nats.url | default (printf "nats://%s-nats:4222" .Release.Name) | quote }}@@ -300,17 +315,10 @@ spec:# packages/sie_gateway/docs/architecture-guide.md section 4.- name: SIE_CONFIG_SERVICE_URLvalue: {{ include "sie-cluster.config.internalUrl" . | quote }}- {{- with include "sie-cluster.config.adminTokenSecretName" . }}- # Shared admin secret. Gateway presents it as a bearer token on- # both GET /v1/configs/export (admin-auth) and- # GET /v1/configs/epoch. Both services read the same secret.- - name: SIE_ADMIN_TOKEN- valueFrom:- secretKeyRef:- name: {{ . }}- key: {{ include "sie-cluster.config.adminTokenSecretKey" $ }}- {{- end }}{{- end }}+ # Read-scoped sie-config token for the bootstrap and poll reads. Always+ # set, empty without one, so the gateway never presents SIE_ADMIN_TOKEN.+ {{- include "sie-cluster.config.serviceTokenEnv" . | nindent 12 }}{{- if $payloadStoreUrl }}- name: SIE_PAYLOAD_STORE_URLvalue: {{ $payloadStoreUrl | quote }}diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex 9500c63ba..53c64fb37 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -37,8 +37,10 @@ fast at render time.reason as on the gateway: both create the work streams, first creatorwins, so the chart renders one value onto both. An extraEnv overridehere would move only the workers and silently reintroduce the divergence- the gateway-deployment render guards exist to prevent. */}}-{{- $reservedSidecarEnv := concat $reservedOtelEnv (list "SIE_BUNDLE" "SIE_GPU_COUNT" "SIE_HEALTH_PUBLISH_ENABLED" "SIE_HEALTH_PUBLISH_INTERVAL_MS" "SIE_MACHINE_PROFILE" "SIE_OTEL_LANE" "SIE_POOL" "SIE_STREAM_MAX_AGE_S" "SIE_STREAM_REPLICAS" "SIE_STREAM_STORAGE" "SIE_WORKER_ID") -}}+ the gateway-deployment render guards exist to prevent. The sidecar's+ 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_OTEL_LANE" "SIE_POOL" "SIE_STREAM_MAX_AGE_S" "SIE_STREAM_REPLICAS" "SIE_STREAM_STORAGE" "SIE_WORKER_ID") -}}{{- 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 }}@@ -544,13 +546,7 @@ spec:# /v1/configs/export through adapter IPC.- name: SIE_CONFIG_SERVICE_URLvalue: {{ include "sie-cluster.config.internalUrl" $root | quote }}- {{- with include "sie-cluster.config.adminTokenSecretName" $root }}- - name: SIE_ADMIN_TOKEN- valueFrom:- secretKeyRef:- name: {{ . }}- key: {{ include "sie-cluster.config.adminTokenSecretKey" $root }}- {{- end }}+ {{- include "sie-cluster.config.serviceTokenEnv" $root | nindent 12 }}{{- if $configReconcile.pollIntervalMs }}- name: SIE_WORKER_CONFIG_POLL_INTERVAL_MSvalue: {{ $configReconcile.pollIntervalMs | quote }}diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 868dea18f..ef0c751a3 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -99,9 +99,11 @@ config:# -- Affinity rulesaffinity: {}- # -- Auth. The admin token gates every sie-config /v1/configs/* read and- # write; sie-config, the gateway, and worker sidecars all read it from the- # same Secret (the gateway and sidecars present it to load the catalog).+ # -- Auth. sie-config accepts two tokens on /v1/configs/*: the admin token+ # authorizes every read and write and is wired only into sie-config (admin+ # tooling reads it from its Secret); the read token authorizes reads only,+ # including GET /v1/configs/export, and is the one the gateway and worker+ # sidecars present to load the catalog.auth:# -- Unused: no template reads this key. It is kept so existing values# files stay valid; adminTokenSecretName and generateAdminToken decide the@@ -125,6 +127,22 @@ config:# production sie-config would refuse every /v1/configs request, and any# other value would leave the API unauthenticated.generateAdminToken: true+ # -- Existing Secret with the read token value (key: readTokenSecretKey).+ # When set, it is used unchanged and no Secret is generated. It must not+ # name the admin token's Secret and key (the render fails), because the+ # gateway and worker sidecars would then hold the write credential.+ readTokenSecretName: ""+ readTokenSecretKey: "SIE_CONFIG_READ_TOKEN"+ # -- When readTokenSecretName is empty and sie-config has an admin token,+ # create `<fullname>-config-read-token` with a random 64-character token,+ # with the same absent-key default, reuse check, keep policy, and+ # `helm template` caveat as the admin token (use readTokenSecretName with+ # GitOps). Setting this to false with no readTokenSecretName fails the+ # render while sie-config has an admin token, because the gateway and+ # worker sidecars would have no credential. Without an admin token+ # (generateAdminToken=false in staging, development, or ci) no read token+ # is generated and sie-config serves reads without one.+ generateReadToken: true# -- Liveness/readiness/startup probe timing. The httpGet path/port are# contracts owned by the template (sie-config exposes /healthz and /readyz);@@ -287,17 +305,21 @@ gateway:# replicas Pending on the single- and two-node clusters the chart supports.affinity: {}- # -- Gateway auth (static token). With mode token or static, the gateway- # also accepts the sie-config admin token (config.auth, chart-generated by- # default) on POST, PUT, and DELETE under /v1/pools, /v1/admin, and- # /v1/configs. sie-config, the gateways, the worker sidecars, and anyone who- # can read Secrets in the release namespace hold that token.+ # -- Gateway auth (static token). The gateway does not receive the sie-config+ # admin token; it holds only the sie-config read token (config.auth).auth:# -- Mode: none | staticmode: none# -- Secret with comma-separated tokenstokenSecretName: ""tokenSecretKey: "SIE_AUTH_TOKEN"+ # -- 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).+ adminTokenSecretName: ""+ adminTokenSecretKey: "SIE_ADMIN_TOKEN"# -- Extra environment variables for the gateway pod.#diff --git a/examples/github-actions/push-model-configs.yml b/examples/github-actions/push-model-configs.ymlindex 70c183efb..879c31d1e 100644--- a/examples/github-actions/push-model-configs.yml+++ b/examples/github-actions/push-model-configs.yml@@ -54,6 +54,7 @@ jobs:shell: bashenv:SIE_ADMIN_TOKEN: ${{ secrets.SIE_ADMIN_TOKEN }}+ SIE_GATEWAY_TOKEN: ${{ secrets.SIE_GATEWAY_TOKEN }}run: |set -euo pipefail@@ -135,12 +136,16 @@ jobs:echo "::group::Poll gateway readiness for ${model_id}"local deadline=$(( $(date +%s) + READINESS_TIMEOUT_SECONDS ))+ local gateway_auth=()+ if [ -n "${SIE_GATEWAY_TOKEN:-}" ]; then+ gateway_auth=(--header "Authorization: Bearer ${SIE_GATEWAY_TOKEN}")+ fiwhile : ; dolocal snap httpsnap="$(mktemp)"http="$(curl --silent --show-error \--output "$snap" --write-out '%{http_code}' \- --header "Authorization: Bearer ${SIE_ADMIN_TOKEN}" \+ "${gateway_auth[@]}" \"${SIE_GATEWAY_URL%/}/v1/configs/models/${model_id}/status")"if [ "$http" = "200" ]; thenif python3 -c 'import json,sys;d=json.load(open(sys.argv[1]));sys.exit(0 if d.get("all_bundles_acked") else 1)' "$snap"; thendiff --git a/packages/sie_config/src/sie_config/app_factory.py b/packages/sie_config/src/sie_config/app_factory.pyindex f080d5d26..37932967b 100644--- a/packages/sie_config/src/sie_config/app_factory.py+++ b/packages/sie_config/src/sie_config/app_factory.py@@ -12,6 +12,7 @@ from starlette.responses import Responsefrom sie_config import metrics as sie_metricsfrom sie_config.config_api import router as config_router+from sie_config.config_api import warn_if_read_token_is_admin_tokenfrom sie_config.config_store import ConfigStorefrom sie_config.health import router as health_routerfrom sie_config.managed_metrics import setup_managed_metrics@@ -129,6 +130,7 @@ class AppFactory:async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:"""Application lifespan manager."""logger.info("Starting SIE Config Service")+ warn_if_read_token_is_admin_token()async with (cls._model_registry(app),diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.pyindex 4cb68d4d0..b3703d33d 100644--- a/packages/sie_config/src/sie_config/config_api.py+++ b/packages/sie_config/src/sie_config/config_api.py@@ -174,6 +174,24 @@ def _get_write_lock(app_state: Any) -> asyncio.Lock:return existing_lock+# Exports queue here, one at a time, before they take the write lock. The write+# lock is FIFO, so without this a burst of N exports would put a write behind N+# snapshot builds; with it, a write waits behind at most one.+_APP_STATE_EXPORT_GATE_ATTR = "_config_export_gate"+_APP_STATE_EXPORT_LOOP_ATTR = "_config_export_gate_loop"+++def _get_export_gate(app_state: Any) -> asyncio.Lock:+ """Per-app export single-flight lock, event-loop-bound like the write lock."""+ running_loop = asyncio.get_running_loop()+ existing_gate = getattr(app_state, _APP_STATE_EXPORT_GATE_ATTR, None)+ if existing_gate is None or getattr(app_state, _APP_STATE_EXPORT_LOOP_ATTR, None) is not running_loop:+ existing_gate = asyncio.Lock()+ setattr(app_state, _APP_STATE_EXPORT_GATE_ATTR, existing_gate)+ setattr(app_state, _APP_STATE_EXPORT_LOOP_ATTR, running_loop)+ return existing_gate++def _get_idempotency_state(app_state: Any) -> _IdempotencyState:"""Lazily fetch-or-create the per-app idempotency state.@@ -388,13 +406,21 @@ _PROD_ENVS = frozenset({"prod", "production"})_ENV_SIGNAL_VARS = ("SIE_DEPLOYMENT_ENV", "SIE_ENV")-def _refuse_open_in_prod() -> None:+# Read-scoped credentials, never accepted on a write. `SIE_CONFIG_READ_TOKEN`+# is the one gateways and worker sidecars present and is accepted on every read+# route; `SIE_AUTH_TOKEN` is the inference token and is accepted on every read+# route except the export. `SIE_ADMIN_TOKEN` authorizes reads and writes.+_INFERENCE_ENV_VAR = "SIE_AUTH_TOKEN"+_READ_TOKEN_VARS = ("SIE_CONFIG_READ_TOKEN", _INFERENCE_ENV_VAR)+++def _refuse_open_in_prod(*, write: bool) -> None:"""Raise 403 when no auth token is configured in a production environment."""if any(os.environ.get(var, "").strip().lower() in _PROD_ENVS for var in _ENV_SIGNAL_VARS):+ required = "SIE_ADMIN_TOKEN" if write else "SIE_CONFIG_READ_TOKEN (or SIE_ADMIN_TOKEN)"raise HTTPException(status_code=403,- detail="config service requires SIE_ADMIN_TOKEN/SIE_AUTH_TOKEN in production "- "(refusing to serve unauthenticated)",+ detail=f"config service requires {required} in production (refusing to serve unauthenticated)",)@@ -416,36 +442,51 @@ def _token_matches(presented: str, expected: str) -> bool:return hmac.compare_digest(presented.encode(), expected.encode())-def _check_read_auth(request: Request) -> None:- """Validate read auth (inference token or admin token)."""- auth_token = os.environ.get("SIE_AUTH_TOKEN")+def warn_if_read_token_is_admin_token() -> None:+ """Log a startup warning when the config read token equals the admin token."""+ read_token = os.environ.get("SIE_CONFIG_READ_TOKEN")admin_token = os.environ.get("SIE_ADMIN_TOKEN")- if auth_token is None and admin_token is None:- _refuse_open_in_prod()+ if read_token is not None and admin_token is not None and _token_matches(read_token, admin_token):+ logger.warning(+ "SIE_CONFIG_READ_TOKEN equals SIE_ADMIN_TOKEN, so every holder of the read token can write configs; "+ "give the read token its own value"+ )+++def _configured_read_tokens() -> list[str]:+ return [token for var in _READ_TOKEN_VARS if (token := os.environ.get(var)) is not None]+++def _check_read_auth(request: Request, *, accept_inference_token: bool = True) -> None:+ """Validate read auth (a read-scoped token or the admin token)."""+ configured = {+ var: token for var in (*_READ_TOKEN_VARS, "SIE_ADMIN_TOKEN") if (token := os.environ.get(var)) is not None+ }+ if not configured:+ _refuse_open_in_prod(write=False)return # No auth configured (dev / self-host localhost posture)token = _extract_bearer_token(request.headers.get("Authorization", ""))if not token:raise HTTPException(status_code=401, detail="Missing Authorization header")- token_match = (auth_token is not None and _token_matches(token, auth_token)) or (- admin_token is not None and _token_matches(token, admin_token)- )- if not token_match:+ accepted = [expected for var, expected in configured.items() if accept_inference_token or var != _INFERENCE_ENV_VAR]+ matches = [_token_matches(token, expected) for expected in accepted]+ if not any(matches):raise HTTPException(status_code=403, detail="Invalid token")def _check_write_auth(request: Request) -> None:- """Validate write auth (admin token, or inference token as fallback)."""+ """Validate write auth (admin token only)."""admin_token = os.environ.get("SIE_ADMIN_TOKEN")if admin_token is None:- # If SIE_ADMIN_TOKEN is not set, refuse writes when SIE_AUTH_TOKEN- # is present (inference token must not implicitly grant write access).- if os.environ.get("SIE_AUTH_TOKEN"):+ # A configured read-scoped token never implies write access, so writes+ # stay closed rather than falling through to the open dev posture.+ if _configured_read_tokens():raise HTTPException(status_code=403,- detail="Write operations require SIE_ADMIN_TOKEN (inference token is not sufficient).",+ detail="Write operations require SIE_ADMIN_TOKEN (read tokens are not sufficient).",)- _refuse_open_in_prod()+ _refuse_open_in_prod(write=True)return # No auth configured at all (dev / self-host localhost posture)token = _extract_bearer_token(request.headers.get("Authorization", ""))@@ -1593,17 +1634,27 @@ async def export_snapshot(request: Request) -> Response:We enforce consistency the cheapest way: take the per-app writelock around the snapshot. Writers serialize on the same lock so- the snapshot is always "between writes". Export is a rare- operation (gateway bootstrap + drift recovery), so the brief- write-path blockage is acceptable. Read-path handlers like- `/epoch`, `/models`, `/bundles` remain fully concurrent.+ the snapshot is always "between writes". Each build blocks writes+ for its duration, so exports first pass a per-app single-flight+ gate: concurrent exports build one at a time and a write waits+ behind at most one build, however many exports are queued.+ Read-path handlers like `/epoch`, `/models`, `/bundles` remain+ fully concurrent.++ Auth: the snapshot carries the same model configs that+ `GET /v1/configs/models/{id}` serves, plus bundle membership, pool names+ and hashes, so gateways and worker sidecars fetch it with the config+ read token (`SIE_CONFIG_READ_TOKEN`). The admin token also works. The+ inference token (`SIE_AUTH_TOKEN`) does not, because each build holds+ the write lock."""- _check_write_auth(request) # admin-only+ _check_read_auth(request, accept_inference_token=False)model_registry = _require_model_registry(request)config_store: ConfigStore | None = getattr(request.app.state, "config_store", None)+ export_gate = _get_export_gate(request.app.state)write_lock = _get_write_lock(request.app.state)- async with write_lock:+ async with export_gate, write_lock:epoch = (await asyncio.to_thread(config_store.read_epoch)) if config_store else 0api_models = set(await asyncio.to_thread(config_store.list_models)) if config_store else set()diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.pyindex 9f547fb85..fa989858f 100644--- a/packages/sie_config/tests/test_config_api.py+++ b/packages/sie_config/tests/test_config_api.py@@ -1,4 +1,5 @@import asyncio+import loggingimport tempfileimport threadingfrom pathlib import Path@@ -8,6 +9,7 @@ import pytestimport yamlfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from sie_config import config_apifrom sie_config.config_api import router as config_routerfrom sie_config.config_store import ConfigStorefrom sie_config.model_registry import ModelRegistry@@ -612,14 +614,19 @@ class TestConfigAPIEdgeCases:# armed by EITHER env signal (SIE_ENV managed / SIE_DEPLOYMENT_ENV Helm).monkeypatch.delenv("SIE_ADMIN_TOKEN", raising=False)monkeypatch.delenv("SIE_AUTH_TOKEN", raising=False)+ monkeypatch.delenv("SIE_CONFIG_READ_TOKEN", raising=False)monkeypatch.delenv("SIE_ENV", raising=False)monkeypatch.delenv("SIE_DEPLOYMENT_ENV", raising=False)monkeypatch.setenv(env_var, "production")app = _create_test_app(self._bundles, self._models)client = TestClient(app)yaml_body = "sie_id: test/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.bert_flash:B\n max_batch_tokens: 1\n"- assert client.get("/v1/configs/models").status_code == 403- assert client.post("/v1/configs/models", content=yaml_body).status_code == 403+ read = client.get("/v1/configs/models")+ assert read.status_code == 403+ assert "requires SIE_CONFIG_READ_TOKEN (or SIE_ADMIN_TOKEN) in production" in read.text+ write = client.post("/v1/configs/models", content=yaml_body)+ assert write.status_code == 403+ assert "requires SIE_ADMIN_TOKEN in production" in write.textdef test_non_ascii_token_is_rejected_not_an_error(self, monkeypatch) -> None:monkeypatch.setenv("SIE_ADMIN_TOKEN", "admin-secret")@@ -635,6 +642,7 @@ class TestConfigAPIEdgeCases:# Self-host / dev (no prod env signal) keeps the open-localhost posture.monkeypatch.delenv("SIE_ADMIN_TOKEN", raising=False)monkeypatch.delenv("SIE_AUTH_TOKEN", raising=False)+ monkeypatch.delenv("SIE_CONFIG_READ_TOKEN", raising=False)monkeypatch.delenv("SIE_ENV", raising=False)monkeypatch.delenv("SIE_DEPLOYMENT_ENV", raising=False)app = _create_test_app(self._bundles, self._models)@@ -1110,7 +1118,7 @@ class TestConfigAPIExportNoConfigStore:class TestConfigAPIExportAuth:- """Export is admin-gated. These tests protect the internal-only contract."""+ """Export bearer parsing, and the admin token on the export route."""def setup_method(self) -> None:self._tmpdir = tempfile.TemporaryDirectory()@@ -1158,18 +1166,6 @@ class TestConfigAPIExportAuth:)assert resp.status_code == 403- def test_export_forbidden_with_inference_only_token(self, monkeypatch) -> None:- # SIE_AUTH_TOKEN alone is not an admin credential, even for reads that- # go through the write-auth gate (export is admin-only).- monkeypatch.delenv("SIE_ADMIN_TOKEN", raising=False)- monkeypatch.setenv("SIE_AUTH_TOKEN", "inference-token")- resp = self.client.get(- "/v1/configs/export",- headers={"Authorization": "Bearer inference-token"},- )- assert resp.status_code == 403- assert "SIE_ADMIN_TOKEN" in resp.text-def test_export_allowed_with_correct_admin_token(self, monkeypatch) -> None:monkeypatch.setenv("SIE_ADMIN_TOKEN", "the-real-admin")resp = self.client.get(@@ -1182,6 +1178,226 @@ class TestConfigAPIExportAuth:assert any(m["model_id"] == "test/model" for m in data["models"])+_WRITE_BODY = (+ "sie_id: test/model\n"+ "profiles:\n"+ " extra:\n"+ " adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"+ " max_batch_tokens: 1\n"+)+_READ_ROUTES = [+ ("GET", "/v1/configs/models", None),+ ("GET", "/v1/configs/models/test/model", None),+ ("GET", "/v1/configs/bundles", None),+ ("GET", "/v1/configs/bundles/default", None),+ ("POST", "/v1/configs/resolve", '{"model": "test/model"}'),+ ("GET", "/v1/configs/epoch", None),+]+_EXPORT_ROUTE = ("GET", "/v1/configs/export", None)+_WRITE_ROUTES = [+ ("POST", "/v1/configs/models", _WRITE_BODY),+ ("PUT", "/v1/configs/models/test/model", _WRITE_BODY),+ ("DELETE", "/v1/configs/models/test/model", None),+]+_CREDENTIALS = {+ "admin": "Bearer admin-secret",+ "config-read": "Bearer config-read-secret",+ "inference": "Bearer inference-secret",+ "wrong": "Bearer not-a-configured-token",+ "non-ascii": "Bearer café".encode(),+}+++class TestConfigAPIRouteAuth:+ """Every route against every credential, with all three tokens configured."""++ def setup_method(self) -> None:+ self._tmpdir = tempfile.TemporaryDirectory()+ root = Path(self._tmpdir.name)+ bundles = root / "bundles"+ models = root / "models"+ bundles.mkdir()+ models.mkdir()+ _write_bundle(bundles, "default", ["sie_server.adapters.bert_flash"])+ _write_model(models, "test/model", "sie_server.adapters.bert_flash:BertFlashAdapter")+ self.client = TestClient(_create_test_app(bundles, models, str(root / "store")))++ def teardown_method(self) -> None:+ self._tmpdir.cleanup()++ @pytest.fixture(autouse=True)+ def _tokens(self, monkeypatch) -> None:+ monkeypatch.setenv("SIE_ADMIN_TOKEN", "admin-secret")+ monkeypatch.setenv("SIE_CONFIG_READ_TOKEN", "config-read-secret")+ monkeypatch.setenv("SIE_AUTH_TOKEN", "inference-secret")+ monkeypatch.setenv("SIE_DEPLOYMENT_ENV", "production")++ def _call(self, method: str, path: str, body: str | None, credential: str | None) -> int:+ headers = {} if credential is None else {"Authorization": _CREDENTIALS[credential]}+ return self.client.request(method, path, content=body, headers=headers).status_code++ @pytest.mark.parametrize(("method", "path", "body"), [*_READ_ROUTES, _EXPORT_ROUTE, *_WRITE_ROUTES])+ def test_missing_credential_is_401(self, method: str, path: str, body: str | None) -> None:+ assert self._call(method, path, body, None) == 401++ @pytest.mark.parametrize("credential", ["wrong", "non-ascii"])+ @pytest.mark.parametrize(("method", "path", "body"), [*_READ_ROUTES, _EXPORT_ROUTE, *_WRITE_ROUTES])+ def test_unknown_credential_is_403(self, method: str, path: str, body: str | None, credential: str) -> None:+ assert self._call(method, path, body, credential) == 403++ @pytest.mark.parametrize("credential", ["admin", "config-read", "inference"])+ @pytest.mark.parametrize(("method", "path", "body"), _READ_ROUTES)+ def test_every_configured_credential_reads(self, method: str, path: str, body: str | None, credential: str) -> None:+ assert self._call(method, path, body, credential) == 200++ @pytest.mark.parametrize(("credential", "status"), [("admin", 200), ("config-read", 200), ("inference", 403)])+ def test_export_accepts_the_config_read_and_admin_tokens_only(self, credential: str, status: int) -> None:+ assert self._call(*_EXPORT_ROUTE, credential) == status++ @pytest.mark.parametrize("credential", ["config-read", "inference"])+ @pytest.mark.parametrize(("method", "path", "body"), _WRITE_ROUTES)+ def test_read_credentials_never_write(self, method: str, path: str, body: str | None, credential: str) -> None:+ assert self._call(method, path, body, credential) == 403++ @pytest.mark.parametrize(("method", "path", "body"), _WRITE_ROUTES)+ def test_admin_credential_writes(self, method: str, path: str, body: str | None) -> None:+ assert self._call(method, path, body, "admin") not in (401, 403)+++class TestConfigAPIReadTokenWithoutAdmin:+ """A read token without an admin token keeps writes closed in any environment."""++ def setup_method(self) -> None:+ self._tmpdir = tempfile.TemporaryDirectory()+ root = Path(self._tmpdir.name)+ bundles = root / "bundles"+ models = root / "models"+ bundles.mkdir()+ models.mkdir()+ _write_bundle(bundles, "default", ["sie_server.adapters.bert_flash"])+ _write_model(models, "test/model", "sie_server.adapters.bert_flash:BertFlashAdapter")+ self.client = TestClient(_create_test_app(bundles, models, str(root / "store")))++ def teardown_method(self) -> None:+ self._tmpdir.cleanup()++ @pytest.mark.parametrize("deployment_env", [None, "development", "production"])+ @pytest.mark.parametrize("read_var", ["SIE_CONFIG_READ_TOKEN", "SIE_AUTH_TOKEN"])+ def test_writes_refused_and_reads_need_the_token(+ self, monkeypatch, read_var: str, deployment_env: str | None+ ) -> None:+ for var in ("SIE_ADMIN_TOKEN", "SIE_CONFIG_READ_TOKEN", "SIE_AUTH_TOKEN", "SIE_ENV", "SIE_DEPLOYMENT_ENV"):+ monkeypatch.delenv(var, raising=False)+ monkeypatch.setenv(read_var, "read-secret")+ if deployment_env is not None:+ monkeypatch.setenv("SIE_DEPLOYMENT_ENV", deployment_env)+ read = {"Authorization": "Bearer read-secret"}++ assert self.client.get("/v1/configs/export").status_code == 401+ export_status = 200 if read_var == "SIE_CONFIG_READ_TOKEN" else 403+ assert self.client.get("/v1/configs/export", headers=read).status_code == export_status+ assert self.client.get("/v1/configs/epoch", headers=read).status_code == 200+ for headers in ({}, read):+ resp = self.client.post("/v1/configs/models", content=_WRITE_BODY, headers=headers)+ assert resp.status_code == 403+ assert "require SIE_ADMIN_TOKEN" in resp.text+ assert self.client.delete("/v1/configs/models/test/model", headers=headers).status_code == 403+++class TestReadTokenSeparationWarning:+ @pytest.mark.parametrize(+ ("read_token", "admin_token", "warned"),+ [("same-secret", "same-secret", True), ("read-secret", "admin-secret", False), (None, "admin-secret", False)],+ )+ def test_warns_only_when_the_read_token_is_the_admin_token(+ self, monkeypatch, caplog, read_token: str | None, admin_token: str, warned: bool+ ) -> None:+ monkeypatch.delenv("SIE_CONFIG_READ_TOKEN", raising=False)+ if read_token is not None:+ monkeypatch.setenv("SIE_CONFIG_READ_TOKEN", read_token)+ monkeypatch.setenv("SIE_ADMIN_TOKEN", admin_token)+ with caplog.at_level(logging.WARNING, logger="sie_config.config_api"):+ config_api.warn_if_read_token_is_admin_token()+ assert ("SIE_CONFIG_READ_TOKEN equals SIE_ADMIN_TOKEN" in caplog.text) is warned+ assert "secret" not in caplog.text+++class TestConfigAPIExportSingleFlight:+ """Concurrent exports build one at a time, so a write waits behind at most one build."""++ def test_a_write_waits_behind_at_most_one_export_build(self, monkeypatch) -> None:+ for var in ("SIE_ADMIN_TOKEN", "SIE_CONFIG_READ_TOKEN", "SIE_AUTH_TOKEN", "SIE_ENV", "SIE_DEPLOYMENT_ENV"):+ monkeypatch.delenv(var, raising=False)+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ bundles, models = root / "bundles", root / "models"+ bundles.mkdir()+ models.mkdir()+ _write_bundle(bundles, "default", ["sie_server.adapters.bert_flash"])+ _write_model(models, "test/model", "sie_server.adapters.bert_flash:BertFlashAdapter")+ app = _create_test_app(bundles, models, str(root / "store"))+ store = app.state.config_store++ order: list[str] = []+ first_build_started = threading.Event()+ release_builds = threading.Event()+ read_epoch, increment_epoch = store.read_epoch, store.increment_epoch+ in_write = threading.local()++ def gated_read_epoch() -> int:+ if getattr(in_write, "active", False):+ return read_epoch()+ order.append("export")+ first_build_started.set()+ assert release_builds.wait(timeout=10)+ return read_epoch()++ def recorded_increment_epoch() -> int:+ order.append("write")+ in_write.active = True+ try:+ return increment_epoch()+ finally:+ in_write.active = False++ monkeypatch.setattr(store, "read_epoch", gated_read_epoch)+ monkeypatch.setattr(store, "increment_epoch", recorded_increment_epoch)+ exports = 8+ lock_requests = 0+ lock_request_events: dict[int, asyncio.Event] = {}+ get_write_lock = config_api._get_write_lock++ def counted_get_write_lock(app_state):+ nonlocal lock_requests+ lock_requests += 1+ if lock_requests in lock_request_events:+ lock_request_events[lock_requests].set()+ return get_write_lock(app_state)++ monkeypatch.setattr(config_api, "_get_write_lock", counted_get_write_lock)++ async def scenario() -> list[int]:+ exports_queued, write_queued = asyncio.Event(), asyncio.Event()+ lock_request_events.update({exports: exports_queued, exports + 1: write_queued})+ transport = httpx.ASGITransport(app=app)+ async with httpx.AsyncClient(transport=transport, base_url="http://sie-config") as client:+ export_tasks = [asyncio.create_task(client.get("/v1/configs/export")) for _ in range(exports)]+ assert await asyncio.to_thread(first_build_started.wait, 10)+ await exports_queued.wait()+ write_task = asyncio.create_task(client.post("/v1/configs/models", content=_WRITE_BODY))+ await write_queued.wait()+ release_builds.set()+ responses = await asyncio.gather(write_task, *export_tasks)+ return [response.status_code for response in responses]++ statuses = asyncio.run(asyncio.wait_for(scenario(), timeout=20))++ assert statuses[0] == 201+ assert statuses[1:] == [200] * exports+ assert order.index("write") == 1, order+ assert order.count("export") == exports++class TestConfigAPIEpoch:"""Lightweight epoch endpoint consumed by the Rust gateway's config poller."""@@ -1300,8 +1516,6 @@ class TestConfigAPIEpoch:assert "epoch" in resp.json()def test_epoch_accepts_admin_token(self, monkeypatch) -> None:- # Read auth accepts the admin token too — the gateway passes its- # admin token here rather than maintaining two credentials.monkeypatch.setenv("SIE_ADMIN_TOKEN", "real-admin")resp = self.client.get("/v1/configs/epoch",diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex d81b0c0e7..b8ea8c2eb 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -93,7 +93,8 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| `SIE_AUTH_MODE` | `none` | Auth mode for inbound requests: `none` disables, `token` (alias `static`) enforces. Unknown values fail-open-to-bypass; `main` logs a startup error naming the bad value || `SIE_AUTH_TOKENS` | | CSV of valid bearer tokens for inference and pool/config read endpoints. If unset, the singular `SIE_AUTH_TOKEN` is used as a fallback. When auth is enabled and this list is empty, non-probe requests return `500` || `SIE_AUTH_TOKEN` | | Singular alias for `SIE_AUTH_TOKENS` (fallback only; prefer the plural form) |-| `SIE_ADMIN_TOKEN` | | Admin bearer token the gateway (1) presents **as a client** to `sie-config` on `GET /v1/configs/export` and `GET /v1/configs/epoch`, and (2) 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` |+| `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_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/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 3b297e038..f965be314 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -79,7 +79,7 @@ Gateway-generated **JSON error** bodies (validation, routing, auth, config read,All config mutations go to `sie-config`. The gateway has no write handler.-1. Admin or deploy tooling sends `POST /v1/configs/models` with a model config YAML body to `sie-config`. Auth: `_check_write_auth` (`packages/sie_config/src/sie_config/config_api.py`) requires a bearer matching `SIE_ADMIN_TOKEN` when that variable is set; if `SIE_ADMIN_TOKEN` is unset and `SIE_AUTH_TOKEN` is set, writes are rejected with `403` (the inference token never grants write access); if neither token is set (dev/local only) writes are accepted unauthenticated. Production deployments always set `SIE_ADMIN_TOKEN`.+1. Admin or deploy tooling sends `POST /v1/configs/models` with a model config YAML body to `sie-config`. Auth: `_check_write_auth` (`packages/sie_config/src/sie_config/config_api.py`) requires a bearer matching `SIE_ADMIN_TOKEN` when that variable is set; if `SIE_ADMIN_TOKEN` is unset and a read-scoped token (`SIE_CONFIG_READ_TOKEN` or `SIE_AUTH_TOKEN`) is set, writes are rejected with `403` (a read token never grants write access); if no token is set (dev/local only) writes are accepted unauthenticated. Production deployments always set `SIE_ADMIN_TOKEN`.2. **Pre-lock validation** (outside the per-app write lock, on the FastAPI event loop): parse the YAML body and — when a top-level `sie_id` is present — run `_validate_model_id` (regex + `..`/`\\` rejection + `status`-suffix rejection). Reject invalid input with `400` before any state is touched. The body is also checked against `packages/sie_config/src/sie_config/model_config.schema.json`, the JSON Schema of the worker's `ModelConfig` (a test keeps the two equal): an unknown key or a wrong value type at any level returns `422 validation_error` with one `{loc, message}` entry per field, instead of accepting a config that every worker rejects. JSON types are applied strictly, so values that pydantic's lax mode would coerce, such as a quoted number, are rejected too. Required fields are not enforced here, since append bodies are partial. `PUT` runs the same check.3. **Critical section** under `_get_write_lock` (a lazy, per-app `asyncio.Lock` stored on `app.state`):1. `ModelRegistry.validate_model_config` — pure check against the in-memory registry (no mutation), run under the registry's internal `threading.RLock`. Validation rejects any write whose post-state resolves to zero routable bundles (`422`), so an `extends`-only profile cannot land a brand-new model that no worker bundle can serve. Appending a new `extends`-only profile to an already-routable model is allowed.@@ -96,7 +96,7 @@ Ordering guarantees:- The epoch is bumped strictly inside the lock, after a successful persist and registry apply. Two concurrent writers cannot lose an epoch bump.- NATS publish happens inside the lock, so the `(bundle_id, epoch)` pairs reach the wire in strict monotonic order per bundle.- No-op replays (every profile already present, no `created_profiles`) skip disk, epoch-bump, and NATS publish entirely. The response still returns normally, reporting `existing_profiles_skipped` with an empty `created_profiles`.-- `GET /v1/configs/export` also takes the same lock (`_check_write_auth` — admin-only), so every exported snapshot is a real serialization point: `(epoch, models)` always corresponds to a state that existed between two writes.+- `GET /v1/configs/export` also takes the same lock, after a per-app single-flight gate that lets one export build at a time, so a write waits behind at most one build however many exports are queued. The lock makes every exported snapshot a real serialization point: `(epoch, models)` always corresponds to a state that existed between two writes.NATS publish behavior:@@ -142,7 +142,7 @@ Startup short-circuits:- If `SIE_CONFIG_SERVICE_URL` is unset, the task logs and returns immediately — there is nothing to bootstrap against. The gateway runs filesystem-seed-only.- If constructing the HTTP client fails, the task sets `sie.gateway.config.bootstrap.degraded` to `1` and returns; it does not retry.-`bootstrap_once` runs a three-call sequence, authenticated with `SIE_ADMIN_TOKEN` as a bearer token on `SIE_CONFIG_SERVICE_URL`:+`bootstrap_once` runs a three-call sequence on `SIE_CONFIG_SERVICE_URL`, authenticated with the gateway's sie-config credential (`SIE_CONFIG_SERVICE_TOKEN`, a read-scoped token) as a bearer token:1. `GET /v1/configs/epoch` — reads the compact control-plane fingerprints BEFORE we fetch bundles, so the hashes we store reflect the state we're about to catch up from (the pre-fetch ordering is load-bearing — see below). The `bundle_config_hashes_hash` fingerprint covers both worker-parity bundle config hashes and model-level pool ownership, because top-level `pool` changes affect routing/readiness even when the worker-applied profile hash is otherwise unchanged.2. `GET /v1/configs/bundles` and per-id `GET /v1/configs/bundles/{id}` — the two-phase bundle fetch. The YAML bodies are parsed into `BundleInfo` values and retained for installation with the model export; this fetch does not install bundles independently.@@ -183,7 +183,7 @@ During the bootstrap-retry window (before the first successful fetch):### 4.2 Epoch poll-`state::config_poller::spawn` runs independently of bootstrap with `DEFAULT_POLL_INTERVAL = 30s`. It skips its first tick (to let the initial bootstrap attempt run without contention), then on every tick calls `GET /v1/configs/epoch` on `sie-config` (always sending `SIE_ADMIN_TOKEN` as the bearer — the `/epoch` handler is read-auth and accepts either `SIE_AUTH_TOKEN` or `SIE_ADMIN_TOKEN`, but the gateway-as-client only presents the admin token). The `/epoch` response carries three drift signals:+`state::config_poller::spawn` runs independently of bootstrap with `DEFAULT_POLL_INTERVAL = 30s`. It skips its first tick (to let the initial bootstrap attempt run without contention), then on every tick calls `GET /v1/configs/epoch` on `sie-config` (sending the same `SIE_CONFIG_SERVICE_TOKEN` bearer; `/epoch`, like every sie-config read route, accepts `SIE_CONFIG_READ_TOKEN`, `SIE_AUTH_TOKEN`, or `SIE_ADMIN_TOKEN`). The `/epoch` response carries three drift signals:- `epoch` — monotonic counter bumped on every model-config write.- `bundles_hash` — sha256 fingerprint over `sie-config`'s loaded bundle set. Bundles are filesystem artifacts inside the `sie-config` image, so their effective "version" is redeploy time, which the model-write counter does not observe.@@ -509,7 +509,8 @@ Gateway (`sie-gateway`):- `SIE_BUNDLES_DIR`, `SIE_MODELS_DIR` — optional filesystem seed paths. Unset by default; only set by the `gateway.embeddedConfigs` / `gateway.configMap` Helm overlays which mount a ConfigMap at `/configs/{bundles,models}`. When unset, the registry's filesystem reload finds nothing and `state::config_bootstrap` fills both bundle and model state from `sie-config`.- `SIE_CONFIG_SERVICE_URL` — base URL of `sie-config`. When set, `/readyz` returns `503` until the first complete export is applied. If unset, the bootstrap and poller tasks no-op and the gateway runs with whatever the (optional) filesystem seed loaded — typically empty in the default deploy, which means **no models will be served**. This is intended for local single-process tests only.-- `SIE_ADMIN_TOKEN` — (1) bearer token the gateway-as-client presents on `GET /v1/configs/export` and `GET /v1/configs/epoch`; (2) the token that `AuthLayer` requires for admin-gated mutations on the gateway itself (`POST/PUT/DELETE` on `/v1/configs/*`, `/v1/admin/*`, `/v1/pools/*`). If empty and the matching inbound request targets an admin path, the middleware fails closed with `403`. On outbound calls, if empty, no `Authorization` header is sent (so `sie-config` must either be unauthenticated or the gateway will fail with `401`/`403`). `sie-config` accepts one admin token at a time and every component reads it at start, so a rotation restarts `sie-config` first and then the gateways and worker sidecars; until they restart, they receive `403` on config reads.+- `SIE_CONFIG_SERVICE_TOKEN` — bearer token the gateway-as-client presents on its `sie-config` reads (`GET /v1/configs/bundles`, `/bundles/{id}`, `/export`, `/epoch`). It should be `sie-config`'s read-scoped token (`SIE_CONFIG_READ_TOKEN` there), which the chart generates and always wires in (empty when the chart runs no `sie-config`). When the variable is set it decides, and a blank value sends no `Authorization` header (so `sie-config` must either be unauthenticated or the gateway will fail with `401`/`403`). When it is unset, the gateway falls back to `SIE_ADMIN_TOKEN` and, when `SIE_CONFIG_SERVICE_URL` is set, logs a deprecation warning at startup; it logs the same warning when the two are equal. `sie-config` accepts one read token at a time and every component reads it at start, so a rotation restarts `sie-config` first and then the gateways and worker sidecars; until they restart, they receive `403` on config reads.+- `SIE_ADMIN_TOKEN` — the token that `AuthLayer` requires for admin-gated mutations on the gateway itself (`POST/PUT/DELETE` on `/v1/configs/*`, `/v1/admin/*`, `/v1/pools/*`). If empty and the matching inbound request targets an admin path, the middleware fails closed with `403`. It is not sent to `sie-config` unless `SIE_CONFIG_SERVICE_TOKEN` is unset (the deprecated fallback above). The chart wires it only from `gateway.auth.adminTokenSecretName`, never from the `sie-config` admin token.- `SIE_AUTH_TOKEN` / `SIE_AUTH_TOKENS` — tokens accepted by the gateway's own inference API (`/v1/encode`, `/v1/score`, `/v1/extract`) and for read-side pool/config routes. Not used for outbound calls to `sie-config`. When `SIE_AUTH_MODE` enables auth but this list is empty, every non-probe request returns `500`.- `SIE_AUTH_MODE` — `token` (alias: `static`) enforces auth; `none` (default) disables it. Typos are fail-open-to-bypass by design; `audit_auth` logs a startup error naming the bad value so operators see it in `kubectl logs`.- `SIE_AUTH_EXEMPT_OPERATIONAL` — when `true`, `/`, `/health`, and `/ws/*` are exempt from auth (they expose worker URLs, bundle assignments, queue depth, GPU inventory — treat as sensitive). Default `false`. **`/healthz` and `/readyz` are always exempt from auth** so kubelet probes never fail with **`401`/`403`** because of a missing bearer token. `/readyz` reports only process readiness and, when `SIE_CONFIG_SERVICE_URL` is set, first-bootstrap completion; worker health remains visible through `/health` and inference responses.@@ -519,8 +520,9 @@ Gateway (`sie-gateway`):Config service (`sie-config`):-- `SIE_ADMIN_TOKEN` — write-auth. Without it, writes are rejected if `SIE_AUTH_TOKEN` is also set (inference token cannot implicitly grant write access). If neither token is set, writes are accepted unauthenticated — dev/local only; production always sets `SIE_ADMIN_TOKEN`.-- `SIE_AUTH_TOKEN` — read-auth. Optional.+- `SIE_ADMIN_TOKEN` — write-auth, and also accepted on every read. Without it, writes are rejected if a read-scoped token (`SIE_CONFIG_READ_TOKEN` or `SIE_AUTH_TOKEN`) is set (a read token cannot implicitly grant write access). If no token is set, reads and writes are accepted unauthenticated — dev/local only; production always sets `SIE_ADMIN_TOKEN`.+- `SIE_CONFIG_READ_TOKEN` — read-auth for the gateways and worker sidecars, which present it as `SIE_CONFIG_SERVICE_TOKEN`. Accepted on every read route, including `GET /v1/configs/export`, and never on a write.+- `SIE_AUTH_TOKEN` — read-auth (the inference token) on every read route except `GET /v1/configs/export`, which holds the write lock and accepts only `SIE_CONFIG_READ_TOKEN` or `SIE_ADMIN_TOKEN`. Optional; the chart does not set it.- `SIE_NATS_URL` — NATS broker URL. Publisher degrades gracefully if unreachable; mutations are blocked with `503` while the publisher is configured but disconnected.- `SIE_CONFIG_STORE_DIR` — base directory for the on-disk config store. When the Helm `config.configStore.enabled` flag is true, this is set to the mounted PVC path and `SIE_CONFIG_RESTORE=true` enables startup replay from the store into the in-memory registry.- `SIE_BUNDLES_DIR`, `SIE_MODELS_DIR` — bundle and model source directories. **`sie-config` is the source of truth**: it reads these at startup, validates writes against them, and re-serves the bundle list at `GET /v1/configs/bundles` for the gateway's bootstrap. Defaults via `sharedPaths.{bundlesDir,modelsDir}` (`/app/bundles`, `/app/models`) and image-baked.@@ -566,12 +568,13 @@ Not registered on the gateway: `POST /v1/configs/models`, `GET /v1/configs/expor### `sie-config`-Config writes (admin auth):+Config writes (admin auth: `SIE_ADMIN_TOKEN`):- `POST /v1/configs/models`-- `GET /v1/configs/export`+- `PUT /v1/configs/models/{model_id:path}`+- `DELETE /v1/configs/models/{model_id:path}`-Config reads (read auth unless noted):+Config reads (read auth: `SIE_CONFIG_READ_TOKEN`, `SIE_AUTH_TOKEN`, or `SIE_ADMIN_TOKEN`):- `GET /v1/configs/models`- `GET /v1/configs/models/{model_id:path}`@@ -579,6 +582,7 @@ Config reads (read auth unless noted):- `GET /v1/configs/bundles/{bundle_id}`- `POST /v1/configs/resolve`- `GET /v1/configs/epoch`+- `GET /v1/configs/export` — `SIE_CONFIG_READ_TOKEN` or `SIE_ADMIN_TOKEN` only`sie-config` does not serve `GET /v1/configs/models/{id}/status`. That endpoint is gateway-only by design (no worker registry on `sie-config`).diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex ea6799809..e5aeef152 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -208,10 +208,11 @@ pub struct Config {// examples); production Helm always sets this.pub config_service_url: Option<String>,- // Admin token the gateway presents as a bearer credential when calling- // `sie-config`'s bootstrap endpoints (`GET /v1/configs/export` and- // `GET /v1/configs/epoch`). Reuses SIE_ADMIN_TOKEN because both services- // share one admin secret in-cluster.+ // Bearer the gateway presents to `sie-config` on its bootstrap and poll+ // reads (`GET /v1/configs/bundles`, `/export`, `/epoch`), from+ // `SIE_CONFIG_SERVICE_TOKEN`: a read-scoped sie-config token+ // (`SIE_CONFIG_READ_TOKEN` there), separate from the inbound `admin_token`.+ // Falls back to `SIE_ADMIN_TOKEN` only when that variable is unset.pub config_service_token: Option<String>,// Optional Modal platform proxy-auth token the gateway's config client@@ -298,7 +299,7 @@ impl std::fmt::Debug for Config {.field("bundles_dir", &self.bundles_dir).field("models_dir", &self.models_dir).field("config_service_url", &self.config_service_url)- // Secret: same admin bearer as `admin_token`; keep present/absent.+ // Secret: the sie-config bearer; keep present/absent..field("config_service_token",&self.config_service_token.as_ref().map(|_| "<redacted>"),@@ -669,6 +670,19 @@ fn env_default(key: &str, fallback: &str) -> String {}}+/// The bearer the gateway presents to `sie-config`. `SIE_CONFIG_SERVICE_TOKEN`+/// decides whenever it is set, and a blank value means no credential. Only an+/// unset `SIE_CONFIG_SERVICE_TOKEN` falls back to `SIE_ADMIN_TOKEN`, the+/// inbound admin credential; `Config::audit_auth` reports that fallback.+fn config_service_token_from_env() -> Option<String> {+ let raw = if env::var_os("SIE_CONFIG_SERVICE_TOKEN").is_some() {+ env::var("SIE_CONFIG_SERVICE_TOKEN").unwrap_or_default()+ } else {+ env::var("SIE_ADMIN_TOKEN").unwrap_or_default()+ };+ (!raw.trim().is_empty()).then_some(raw)+}+impl Config {pub fn load() -> Self {let mut auth_tokens = env_csv("SIE_AUTH_TOKENS");@@ -757,14 +771,7 @@ impl Config {Some(raw)}},- config_service_token: {- let raw = env::var("SIE_ADMIN_TOKEN").unwrap_or_default();- if raw.is_empty() {- None- } else {- Some(raw)- }- },+ config_service_token: config_service_token_from_env(),config_modal_proxy_token: {// #1740: opt-in Modal platform proxy-auth. Both halves required// for the pair to be sent — a half-set pair is a misconfig, not@@ -833,19 +840,35 @@ impl Config {));}- // `admin_token` alone is not dead configuration: `Config::load` also- // presents it to `sie-config` as the bootstrap credential- // (`config_service_token`), so a gateway with inbound auth off still- // legitimately carries it. Only the inbound tokens prove intent.+ let admin_is_config_credential = has_admin+ && self.config_service_url.is_some()+ && self.config_service_token.as_deref() == Some(self.admin_token.as_str());++ // `admin_token` alone is not dead configuration while it is also the+ // `sie-config` credential, so it never audits as an error. Only the+ // inbound tokens prove intent. Without `config_service_url` the+ // gateway never calls `sie-config`, so no credential is presented.if !is_enabled && has_tokens {issues.push((AuditLevel::Error,"SIE_AUTH_TOKEN(S) is set but SIE_AUTH_MODE is not 'static'/'token'. Auth is DISABLED; the tokens are dead configuration. Set SIE_AUTH_MODE=token to enforce auth.".to_string(),));} else if !is_enabled && has_admin {+ let usage = if admin_is_config_credential {+ "the token is still presented to sie-config as its credential"+ } else {+ "the token is unused"+ };issues.push((AuditLevel::Warn,- "SIE_ADMIN_TOKEN is set but SIE_AUTH_MODE is not 'static'/'token': admin routes are not gated inbound (auth is disabled); the token is still presented to sie-config as the bootstrap credential.".to_string(),+ format!("SIE_ADMIN_TOKEN is set but SIE_AUTH_MODE is not 'static'/'token': admin routes are not gated inbound (auth is disabled); {usage}."),+ ));+ }++ if admin_is_config_credential {+ issues.push((+ AuditLevel::Warn,+ "The gateway presents SIE_ADMIN_TOKEN, its inbound admin credential, to sie-config because SIE_CONFIG_SERVICE_TOKEN is unset or equal to it. This is deprecated: set SIE_CONFIG_SERVICE_TOKEN to sie-config's read-scoped token (SIE_CONFIG_READ_TOKEN) so the gateway does not need an admin credential to load its catalog.".to_string(),));}@@ -1639,22 +1662,106 @@ mod tests {assert_eq!(StreamStorage::parse("s3"), None);}- #[test]- fn test_admin_token_populates_config_service_token() {- with_env(&[("SIE_ADMIN_TOKEN", "super-secret")], || {- let cfg = Config::load();- assert_eq!(cfg.admin_token, "super-secret");- assert_eq!(cfg.config_service_token.as_deref(), Some("super-secret"));+ const CONFIG_CREDENTIAL_VARS: &[&str] = &[+ "SIE_CONFIG_SERVICE_URL",+ "SIE_CONFIG_SERVICE_TOKEN",+ "SIE_ADMIN_TOKEN",+ ];+ const CONFIG_URL: (&str, &str) = ("SIE_CONFIG_SERVICE_URL", "http://sie-config:8080");++ fn load_with_config_credentials(vars: &[(&str, &str)]) -> Config {+ let mut loaded = None;+ without_env(CONFIG_CREDENTIAL_VARS, || {+ for (key, value) in vars {+ env::set_var(key, value);+ }+ loaded = Some(Config::load());});+ loaded.expect("Config::load ran")+ }++ fn deprecation_warnings(cfg: &Config) -> usize {+ cfg.audit_auth()+ .iter()+ .filter(|(lvl, msg)| *lvl == AuditLevel::Warn && msg.contains("deprecated"))+ .count()}#[test]- fn test_admin_token_unset_leaves_config_service_token_none() {- without_env(&["SIE_ADMIN_TOKEN"], || {- let cfg = Config::load();- assert!(cfg.admin_token.is_empty());- assert!(cfg.config_service_token.is_none());- });+ fn test_config_service_token_is_separate_from_the_admin_token() {+ let cfg = load_with_config_credentials(&[+ CONFIG_URL,+ ("SIE_CONFIG_SERVICE_TOKEN", "config-read-secret"),+ ("SIE_ADMIN_TOKEN", "gateway-admin-secret"),+ ]);+ assert_eq!(cfg.admin_token, "gateway-admin-secret");+ assert_eq!(+ cfg.config_service_token.as_deref(),+ Some("config-read-secret")+ );+ assert_eq!(deprecation_warnings(&cfg), 0);+ }++ #[test]+ fn test_config_service_token_without_an_admin_token() {+ let cfg =+ load_with_config_credentials(&[("SIE_CONFIG_SERVICE_TOKEN", "config-read-secret")]);+ assert!(cfg.admin_token.is_empty());+ assert_eq!(+ cfg.config_service_token.as_deref(),+ Some("config-read-secret")+ );+ }++ #[test]+ fn test_unset_config_service_token_falls_back_to_the_admin_token() {+ let cfg = load_with_config_credentials(&[CONFIG_URL, ("SIE_ADMIN_TOKEN", "super-secret")]);+ assert_eq!(cfg.admin_token, "super-secret");+ assert_eq!(cfg.config_service_token.as_deref(), Some("super-secret"));+ assert_eq!(deprecation_warnings(&cfg), 1);+ assert!(cfg.auth_config_error().is_none());+ }++ #[test]+ fn test_admin_token_without_a_config_service_is_not_reported_as_the_config_credential() {+ let cfg = load_with_config_credentials(&[("SIE_ADMIN_TOKEN", "super-secret")]);+ assert!(cfg.config_service_url.is_none());+ assert_eq!(deprecation_warnings(&cfg), 0);+ assert!(!cfg+ .audit_auth()+ .iter()+ .any(|(_, msg)| msg.contains("presented to sie-config")));+ }++ #[test]+ fn test_blank_config_service_token_does_not_fall_back() {+ for blank in ["", " "] {+ let cfg = load_with_config_credentials(&[+ CONFIG_URL,+ ("SIE_CONFIG_SERVICE_TOKEN", blank),+ ("SIE_ADMIN_TOKEN", "gateway-admin-secret"),+ ]);+ assert_eq!(cfg.admin_token, "gateway-admin-secret");+ assert!(cfg.config_service_token.is_none(), "{blank:?}");+ assert_eq!(deprecation_warnings(&cfg), 0);+ }+ }++ #[test]+ fn test_no_config_service_credential() {+ let cfg = load_with_config_credentials(&[]);+ assert!(cfg.admin_token.is_empty());+ assert!(cfg.config_service_token.is_none());+ }++ #[test]+ fn test_config_service_token_equal_to_the_admin_token_is_reported() {+ let cfg = load_with_config_credentials(&[+ CONFIG_URL,+ ("SIE_CONFIG_SERVICE_TOKEN", "shared-secret"),+ ("SIE_ADMIN_TOKEN", "shared-secret"),+ ]);+ assert_eq!(deprecation_warnings(&cfg), 1);}#[test]@@ -1726,14 +1833,15 @@ mod tests {fn test_config_debug_redacts_all_secret_fields() {// `Config` is `{:?}`-formatted at startup (and in tests), so EVERY// credential-bearing field must be redacted: the client API bearers- // (auth_tokens), the admin bearer (admin_token AND the config_service_token- // derived from it), and both halves of the Modal proxy token. Non-secret- // fields must stay visible for debuggability.+ // (auth_tokens), the admin bearer (admin_token), the sie-config bearer+ // (config_service_token), and both halves of the proxy token.+ // Non-secret fields must stay visible for debuggability.with_env(&[("SIE_AUTH_MODE", "token"),("SIE_AUTH_TOKENS", "tok-secret-1,tok-secret-2"),("SIE_ADMIN_TOKEN", "super-admin-secret"),+ ("SIE_CONFIG_SERVICE_TOKEN", "config-read-secret"),("SIE_MODAL_PROXY_TOKEN_ID", "wk-id-secret"),("SIE_MODAL_PROXY_TOKEN_SECRET", "ws-value-secret"),("SIE_NATS_URL", "nats://nats-host:4222"),@@ -1745,13 +1853,14 @@ mod tests {assert_eq!(cfg.admin_token, "super-admin-secret");assert_eq!(cfg.config_service_token.as_deref(),- Some("super-admin-secret")+ Some("config-read-secret"));assert_eq!(cfg.auth_tokens.len(), 2);let dbg = format!("{cfg:?}");for leaked in [- "super-admin-secret", // admin_token + config_service_token+ "super-admin-secret", // admin_token+ "config-read-secret", // config_service_token"tok-secret-1","tok-secret-2", // auth_tokens"wk-id-secret",@@ -1843,20 +1952,52 @@ mod tests {);}- /// The admin token doubles as the `sie-config` bootstrap credential- /// (`config_service_token`), so a gateway running with inbound auth off- /// still carries it legitimately. That must never audit as an error, or- /// the fail-closed middleware would refuse every request on such a deploy.+ /// Through the `SIE_ADMIN_TOKEN` fallback the admin token can also be the+ /// `sie-config` credential (`config_service_token`), so a gateway running+ /// with inbound auth off may carry it legitimately. That must never audit+ /// as an error, or the fail-closed middleware would refuse every request+ /// on such a deploy.#[test]fn test_audit_auth_none_with_only_admin_token_is_not_an_error() {- let cfg = cfg_with_auth("none", vec![], "admin", false);+ for config_service_token in [None, Some("admin")] {+ let mut cfg = cfg_with_auth("none", vec![], "admin", false);+ cfg.config_service_token = config_service_token.map(String::from);+ let issues = cfg.audit_auth();+ assert!(+ issues.iter().all(|(lvl, _)| *lvl != AuditLevel::Error),+ "admin token alone must not be an error: {:?}",+ issues+ );+ assert!(cfg.auth_config_error().is_none());+ }+ }++ #[test]+ fn test_audit_auth_none_admin_token_usage_follows_the_config_credential() {+ let mut cfg = cfg_with_auth("none", vec![], "admin", false);+ cfg.config_service_url = Some("http://sie-config:8080".to_string());+ cfg.config_service_token = Some("config-read".to_string());let issues = cfg.audit_auth();- assert!(- issues.iter().all(|(lvl, _)| *lvl != AuditLevel::Error),- "admin token alone must not be an error: {:?}",- issues- );- assert!(cfg.auth_config_error().is_none());+ assert!(issues+ .iter()+ .any(|(lvl, msg)| *lvl == AuditLevel::Warn && msg.contains("the token is unused")));+ assert!(!issues.iter().any(|(_, msg)| msg.contains("deprecated")));++ cfg.config_service_token = Some("admin".to_string());+ let issues = cfg.audit_auth();+ assert!(issues+ .iter()+ .any(|(lvl, msg)| *lvl == AuditLevel::Warn && msg.contains("presented to sie-config")));+ assert!(issues+ .iter()+ .any(|(lvl, msg)| *lvl == AuditLevel::Warn && msg.contains("deprecated")));++ cfg.config_service_url = None;+ let issues = cfg.audit_auth();+ assert!(issues+ .iter()+ .any(|(lvl, msg)| *lvl == AuditLevel::Warn && msg.contains("the token is unused")));+ assert!(!issues.iter().any(|(_, msg)| msg.contains("deprecated")));}#[test]diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex a64519e76..0b4de6973 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -742,8 +742,9 @@ mod tests {#[tokio::test]async fn middleware_admin_token_alone_with_disabled_mode_passes_through() {- // `SIE_ADMIN_TOKEN` is also the sie-config bootstrap credential, so- // "auth off + admin token present" is an ordinary deployment shape.+ // With `SIE_CONFIG_SERVICE_TOKEN` unset, `SIE_ADMIN_TOKEN` is also the+ // sie-config credential, so "auth off + admin token present" is an+ // ordinary deployment shape.let cfg = cfg_for_middleware("none", vec![], "admin", false);let r = test_router(cfg);assert_eq!(diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex 372b559e9..18855cacb 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -229,7 +229,7 @@ pub(crate) fn telemetry_outcome(error: &BootstrapError) -> ConfigOutcome {pub struct BootstrapClient {base_url: String,- admin_token: Option<String>,+ token: Option<String>,/// Optional Modal platform proxy-auth token (#1740). When set, every/// request also carries `Modal-Key` / `Modal-Secret` so it clears the/// Modal edge before app code sees it. Absent on self-host / dev.@@ -344,7 +344,7 @@ impl BootstrapOutcome {}impl BootstrapClient {- pub fn new(base_url: String, admin_token: Option<String>) -> Result<Self, String> {+ pub fn new(base_url: String, token: Option<String>) -> Result<Self, String> {let managed_proxy_auth = managed_proxy_auth_enabled();if managed_proxy_auth {validate_managed_config_origin(@@ -357,7 +357,7 @@ impl BootstrapClient {let http = build_config_http_client(managed_proxy_auth)?;Ok(Self {base_url,- admin_token,+ token,modal_proxy_token: None,managed_proxy_auth,http,@@ -375,14 +375,14 @@ impl BootstrapClient {self}- /// Apply both auth layers to a request builder: the in-app admin bearer+ /// Apply both auth layers to a request builder: the sie-config bearer/// (`config_service_token`) and, when configured, the Modal platform/// proxy-auth headers (#1740). The two are independent — the bearer is/// checked by `sie_config`, the `Modal-Key` / `Modal-Secret` pair by the/// Modal edge — so both are sent when present.fn apply_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {let mut req = req;- if let Some(token) = &self.admin_token {+ if let Some(token) = &self.token {req = req.bearer_auth(token);}if let Some(proxy) = &self.modal_proxy_token {@@ -752,7 +752,7 @@ const DEGRADED_AFTER: std::time::Duration = std::time::Duration::from_secs(5 * 6/// `state::config_poller`.pub fn spawn_bootstrap_retry(base_url: Option<&str>,- admin_token: Option<&str>,+ token: Option<&str>,modal_proxy_token: Option<&ModalProxyToken>,registry: Arc<ModelRegistry>,config_epoch: ConfigEpoch,@@ -760,7 +760,7 @@ pub fn spawn_bootstrap_retry(bundle_config_hashes_hash: BundleConfigHashesHash,) -> tokio::task::JoinHandle<()> {let base_url = base_url.map(str::to_string);- let admin_token = admin_token.map(str::to_string);+ let token = token.map(str::to_string);let modal_proxy_token = modal_proxy_token.cloned();tokio::spawn(async move {telemetry::set_config_bootstrap_degraded(false);@@ -768,7 +768,7 @@ pub fn spawn_bootstrap_retry(info!("SIE_CONFIG_SERVICE_URL not set; skipping config bootstrap");return;};- let client = match BootstrapClient::new(base, admin_token)+ let client = match BootstrapClient::new(base, token).map(|c| c.with_modal_proxy_token(modal_proxy_token)){Ok(c) => c,@@ -1408,7 +1408,7 @@ mod tests {let client = BootstrapClient {base_url: server.uri(),- admin_token: Some("admin-secret".into()),+ token: Some("admin-secret".into()),modal_proxy_token: None,managed_proxy_auth: false,http: reqwest::Client::new(),@@ -1444,7 +1444,7 @@ mod tests {let client = BootstrapClient {base_url: origin.uri(),- admin_token: Some("admin-secret".into()),+ token: Some("admin-secret".into()),modal_proxy_token: Some(ModalProxyToken {key: "wk-abc".into(),secret: "ws-xyz".into(),diff --git a/packages/sie_gateway/src/state/config_poller.rs b/packages/sie_gateway/src/state/config_poller.rsindex 6b8a4150a..42e6bc8d0 100644--- a/packages/sie_gateway/src/state/config_poller.rs+++ b/packages/sie_gateway/src/state/config_poller.rs@@ -77,14 +77,14 @@ pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(30);////// Returns `None` if `base_url` is unset (no control plane configured)./// Otherwise returns a handle to the running task.-// The client-wiring args (base_url + admin_token + modal_proxy_token, #1740)+// The client-wiring args (base URL, sie-config token, proxy token)// plus the four reconciliation handles are all independent inputs; bundling// them into a struct would obscure more than it clarifies for a single call// site. Matches the crate's other multi-input spawn/dispatch helpers.#[allow(clippy::too_many_arguments)]pub fn spawn(base_url: Option<&str>,- admin_token: Option<&str>,+ token: Option<&str>,modal_proxy_token: Option<&ModalProxyToken>,registry: Arc<ModelRegistry>,config_epoch: ConfigEpoch,@@ -93,11 +93,11 @@ pub fn spawn(interval: Duration,) -> Option<tokio::task::JoinHandle<()>> {let base = base_url?.to_string();- let admin_token = admin_token.map(str::to_string);+ let token = token.map(str::to_string);let modal_proxy_token = modal_proxy_token.cloned();let handle = tokio::spawn(async move {- let client = match BootstrapClient::new(base, admin_token)+ let client = match BootstrapClient::new(base, token).map(|c| c.with_modal_proxy_token(modal_proxy_token)){Ok(c) => c,diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 6b872b8e7..0fbba0ac8 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -484,6 +484,12 @@ When `SIE_CONFIG_SERVICE_URL` is configured, the export reconciler fetchesexports are sent to the backend through `ReplaceModelConfigs`, with theexport's `bundle_adapters` list for this bundle.+The reconciler authenticates with `SIE_CONFIG_SERVICE_TOKEN`+(`--config-service-token`), `sie-config`'s read-scoped `SIE_CONFIG_READ_TOKEN`,+which cannot write configs. When the variable is set it decides, and a blank+value sends no token. When it is unset, the sidecar falls back to+`SIE_ADMIN_TOKEN` and logs a deprecation warning at startup.+Export reconciliation skips unchanged periodic exports. Exports older than thelocal epoch are skipped unless the reconciler is handling an epoch-rewindrecovery. Partial or rejected replacements do not update the advertised bundlediff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 1b4c56318..21608cfff 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -129,9 +129,8 @@ pub struct WorkerConfig {/// `/v1/configs/export`.pub config_service_url: Option<String>,- /// Optional bearer token for `sie-config` export reads. Helm wires this- /// from `SIE_ADMIN_TOKEN` when config auth is enabled because- /// `/v1/configs/export` is admin-authenticated.+ /// Optional bearer token for the `sie-config` epoch and export reads,+ /// from `SIE_CONFIG_SERVICE_TOKEN`: a read-scoped sie-config token.pub config_service_token: Option<String>,/// Cadence for worker-side `/v1/configs/epoch` polling.@@ -339,10 +338,10 @@ mod tests {fn debug_redacts_bearer_tokens() {let mut c = sample();c.gateway_api_key = Some("gateway-bearer-value".into());- c.config_service_token = Some("config-admin-value".into());+ c.config_service_token = Some("config-read-value".into());let rendered = format!("{c:?}");assert!(!rendered.contains("gateway-bearer-value"));- assert!(!rendered.contains("config-admin-value"));+ assert!(!rendered.contains("config-read-value"));assert!(rendered.contains("config_service_token: Some(\"<redacted>\")"));assert!(rendered.contains("gateway_api_key: Some(\"<redacted>\")"));assert!(rendered.contains("worker_id: \"worker-test\""));diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rsindex 8fddf38df..820ac9d1f 100644--- a/packages/sie_server_sidecar/src/config_reconciler.rs+++ b/packages/sie_server_sidecar/src/config_reconciler.rs@@ -38,7 +38,7 @@ const DEFAULT_MODEL_POOL: &str = "default";#[derive(Clone)]pub struct ReconcilerConfig {pub base_url: String,- pub admin_token: Option<String>,+ pub token: Option<String>,pub bundle: String,pub pool: String,pub poll_interval: Duration,@@ -46,13 +46,13 @@ pub struct ReconcilerConfig {}impl std::fmt::Debug for ReconcilerConfig {- /// Hand-written so `admin_token` prints only as present or absent.+ /// Hand-written so `token` prints only as present or absent.fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {// Destructured without `..` so a new field fails to compile until it is// listed here, and so cannot be printed unredacted or silently omitted.let ReconcilerConfig {base_url,- admin_token,+ token,bundle,pool,poll_interval,@@ -60,7 +60,7 @@ impl std::fmt::Debug for ReconcilerConfig {} = self;f.debug_struct("ReconcilerConfig").field("base_url", base_url)- .field("admin_token", &admin_token.as_ref().map(|_| "<redacted>"))+ .field("token", &token.as_ref().map(|_| "<redacted>")).field("bundle", bundle).field("pool", pool).field("poll_interval", poll_interval)@@ -174,7 +174,7 @@ struct ExportReconcileOptions<'a> {struct ReconcileClient {base_url: String,- admin_token: Option<String>,+ token: Option<String>,http: reqwest::Client,}@@ -195,11 +195,11 @@ struct ReconcileScope<'a> {}impl ReconcileClient {- fn new(base_url: String, admin_token: Option<String>) -> Result<Self, reqwest::Error> {+ fn new(base_url: String, token: Option<String>) -> Result<Self, reqwest::Error> {let http = reqwest::Client::builder().timeout(HTTP_TIMEOUT).build()?;Ok(Self {base_url,- admin_token,+ token,http,})}@@ -207,7 +207,7 @@ impl ReconcileClient {async fn fetch_epoch(&self) -> Result<EpochSnapshot, ReconcileError> {let url = format!("{}/v1/configs/epoch", self.base_url.trim_end_matches('/'));let mut req = self.http.get(&url);- if let Some(token) = &self.admin_token {+ if let Some(token) = &self.token {req = req.bearer_auth(token);}let resp = req.send().await?;@@ -226,7 +226,7 @@ impl ReconcileClient {async fn fetch_export(&self) -> Result<ExportSnapshot, ReconcileError> {let url = format!("{}/v1/configs/export", self.base_url.trim_end_matches('/'));let mut req = self.http.get(&url);- if let Some(token) = &self.admin_token {+ if let Some(token) = &self.token {req = req.bearer_auth(token);}let resp = req.send().await?;@@ -343,7 +343,7 @@ pub fn spawn(}Some(tokio::spawn(async move {- let client = match ReconcileClient::new(config.base_url.clone(), config.admin_token) {+ let client = match ReconcileClient::new(config.base_url.clone(), config.token) {Ok(c) => c,Err(e) => {warn!(error = %e, "worker-config: failed to build export reconciler client");@@ -798,18 +798,18 @@ mod tests {use tokio::sync::Mutex;#[test]- fn reconciler_config_debug_redacts_admin_token() {+ fn reconciler_config_debug_redacts_the_token() {let config = ReconcilerConfig {base_url: "http://sie-config:8080".into(),- admin_token: Some("config-admin-value".into()),+ token: Some("config-read-value".into()),bundle: "default".into(),pool: "default".into(),poll_interval: DEFAULT_POLL_INTERVAL,full_export_interval: Some(DEFAULT_FULL_EXPORT_INTERVAL),};let rendered = format!("{config:?}");- assert!(!rendered.contains("config-admin-value"));- assert!(rendered.contains("admin_token: Some(\"<redacted>\")"));+ assert!(!rendered.contains("config-read-value"));+ assert!(rendered.contains("token: Some(\"<redacted>\")"));assert!(rendered.contains("base_url: \"http://sie-config:8080\""));}diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex d0bb3910c..70affca2e 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -505,7 +505,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {config.config_service_url.as_ref().map(|base_url| {crate::config_reconciler::ReconcilerConfig {base_url: base_url.clone(),- admin_token: config.config_service_token.clone(),+ token: config.config_service_token.clone(),bundle: config.bundle.clone(),pool: config.pool.clone(),poll_interval: Duration::from_millis(config.config_poll_interval_ms),@@ -863,7 +863,7 @@ pub async fn run_local(config: WorkerConfig) -> anyhow::Result<()> {config.config_service_url.as_ref().map(|base_url| {crate::config_reconciler::ReconcilerConfig {base_url: base_url.clone(),- admin_token: config.config_service_token.clone(),+ token: config.config_service_token.clone(),bundle: config.bundle.clone(),pool: config.pool.clone(),poll_interval: Duration::from_millis(config.config_poll_interval_ms),diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rsindex a964bbf32..b6224bb38 100644--- a/packages/sie_server_sidecar/src/main.rs+++ b/packages/sie_server_sidecar/src/main.rs@@ -8,7 +8,7 @@ use std::path::PathBuf;use anyhow::Context;use clap::Parser;-use tracing::{error, info};+use tracing::{error, info, warn};use sie_server_sidecar::config::WorkerConfig;use sie_server_sidecar::config_subscriber::trusted_producers_from_env;@@ -142,9 +142,10 @@ struct Cli {#[arg(long, env = "SIE_CONFIG_SERVICE_URL")]config_service_url: Option<String>,- /// Bearer token for sie-config export reads. Defaults from the shared- /// SIE_ADMIN_TOKEN secret in Helm when config auth is enabled.- #[arg(long, env = "SIE_ADMIN_TOKEN", hide_env_values = true)]+ /// Bearer token for the sie-config epoch and export reads: a read-scoped+ /// sie-config token (SIE_CONFIG_READ_TOKEN there). A blank value sends no+ /// token. When this is unset, SIE_ADMIN_TOKEN is used instead (deprecated).+ #[arg(long, env = "SIE_CONFIG_SERVICE_TOKEN", hide_env_values = true)]config_service_token: Option<String>,/// Worker-side config epoch poll interval in milliseconds.@@ -196,6 +197,19 @@ async fn main() -> anyhow::Result<()> {let ipc_socket_paths = parse_ipc_socket_paths(cli.ipc_socket_paths.as_deref()).unwrap_or_else(|| vec![ipc_socket_path.clone()]);validate_unique_ipc_socket_paths(&ipc_socket_paths)?;+ let config_service_url = cli.config_service_url.filter(|url| !url.trim().is_empty());+ let config_service_token = resolve_config_service_token(+ cli.config_service_token,+ std::env::var_os(CONFIG_SERVICE_TOKEN_ENV).is_some(),+ std::env::var(LEGACY_CONFIG_SERVICE_TOKEN_ENV).ok(),+ );+ if config_service_url.is_some() && config_service_token.from_admin_token {+ warn!(+ "sie-config credential taken from {LEGACY_CONFIG_SERVICE_TOKEN_ENV} because \+ {CONFIG_SERVICE_TOKEN_ENV} is unset; this is deprecated, set \+ {CONFIG_SERVICE_TOKEN_ENV} to sie-config's read-scoped token (SIE_CONFIG_READ_TOKEN)"+ );+ }let config = WorkerConfig {nats_url: cli.nats_url,local_socket_path: cli.local_socket.map(Into::into),@@ -228,10 +242,8 @@ async fn main() -> anyhow::Result<()> {machine_profile,gpu_count: cli.gpu_count,bundle_config_hash: cli.bundle_config_hash,- config_service_url: cli.config_service_url.filter(|url| !url.trim().is_empty()),- config_service_token: cli- .config_service_token- .filter(|token| !token.trim().is_empty()),+ config_service_url,+ config_service_token: config_service_token.token,config_poll_interval_ms: cli.config_poll_interval_ms.max(1_000),config_full_export_interval_ms: cli.config_full_export_interval_ms,nats_config_trusted_producers: trusted_producers_from_env(),@@ -267,6 +279,36 @@ async fn main() -> anyhow::Result<()> {Ok(())}+const CONFIG_SERVICE_TOKEN_ENV: &str = "SIE_CONFIG_SERVICE_TOKEN";+const LEGACY_CONFIG_SERVICE_TOKEN_ENV: &str = "SIE_ADMIN_TOKEN";++struct ConfigServiceToken {+ token: Option<String>,+ from_admin_token: bool,+}++/// `--config-service-token` / `SIE_CONFIG_SERVICE_TOKEN` decides whenever it is+/// set, and a blank value means no token. Only when it is unset does the+/// sidecar fall back to `SIE_ADMIN_TOKEN`.+fn resolve_config_service_token(+ configured: Option<String>,+ configured_env_is_set: bool,+ admin_token: Option<String>,+) -> ConfigServiceToken {+ let non_blank = |token: String| (!token.trim().is_empty()).then_some(token);+ if configured.is_some() || configured_env_is_set {+ return ConfigServiceToken {+ token: configured.and_then(non_blank),+ from_admin_token: false,+ };+ }+ let token = admin_token.and_then(non_blank);+ ConfigServiceToken {+ from_admin_token: token.is_some(),+ token,+ }+}+fn init_tracing() {sie_server_sidecar::observability::tracing::init_tracing();}@@ -398,6 +440,7 @@ mod tests {use std::path::PathBuf;use super::parse_ipc_socket_paths;+ use super::resolve_config_service_token;use super::validate_ingest_mode;use super::validate_lane_segment;use super::validate_model_ready_liveness_budget;@@ -423,11 +466,53 @@ mod tests {secret_args,vec![("SIE_GATEWAY_API_KEY".to_string(), true),- ("SIE_ADMIN_TOKEN".to_string(), true),+ ("SIE_CONFIG_SERVICE_TOKEN".to_string(), true),]);}+ fn resolved(+ configured: Option<&str>,+ configured_env_is_set: bool,+ admin_token: Option<&str>,+ ) -> (Option<String>, bool) {+ let resolved = resolve_config_service_token(+ configured.map(String::from),+ configured_env_is_set,+ admin_token.map(String::from),+ );+ (resolved.token, resolved.from_admin_token)+ }++ #[test]+ fn config_service_token_is_preferred_over_the_admin_token() {+ assert_eq!(+ resolved(Some("config-read"), true, Some("admin")),+ (Some("config-read".to_string()), false)+ );+ assert_eq!(+ resolved(Some("config-read"), false, Some("admin")),+ (Some("config-read".to_string()), false)+ );+ }++ #[test]+ fn a_set_but_blank_config_service_token_sends_no_token() {+ for blank in [Some(""), Some(" "), None] {+ assert_eq!(resolved(blank, true, Some("admin")), (None, false));+ }+ }++ #[test]+ fn an_unset_config_service_token_falls_back_to_the_admin_token() {+ assert_eq!(+ resolved(None, false, Some("admin")),+ (Some("admin".to_string()), true)+ );+ assert_eq!(resolved(None, false, Some(" ")), (None, false));+ assert_eq!(resolved(None, false, None), (None, false));+ }+#[test]fn ingest_mode_nats_requires_nats_url() {assert_eq!(diff --git a/packages/sie_server_sidecar/tests/cli_help.rs b/packages/sie_server_sidecar/tests/cli_help.rsindex 9f4d0562f..53cf321de 100644--- a/packages/sie_server_sidecar/tests/cli_help.rs+++ b/packages/sie_server_sidecar/tests/cli_help.rs@@ -4,14 +4,16 @@ use std::process::Command;fn help_does_not_print_secret_env_values() {let output = Command::new(env!("CARGO_BIN_EXE_sie-server-sidecar")).arg("--help")+ .env("SIE_CONFIG_SERVICE_TOKEN", "config-token-in-env").env("SIE_ADMIN_TOKEN", "admin-token-in-env").env("SIE_GATEWAY_API_KEY", "gateway-key-in-env").output().expect("run sie-server-sidecar --help");assert!(output.status.success(), "{output:?}");let help = String::from_utf8(output.stdout).expect("utf-8 help");- assert!(help.contains("SIE_ADMIN_TOKEN"));+ assert!(help.contains("SIE_CONFIG_SERVICE_TOKEN"));assert!(help.contains("SIE_GATEWAY_API_KEY"));+ assert!(!help.contains("config-token-in-env"));assert!(!help.contains("admin-token-in-env"));assert!(!help.contains("gateway-key-in-env"));}diff --git a/tools/ci/cpu_stack_smoke.py b/tools/ci/cpu_stack_smoke.pyindex 921986a0b..d716f00ff 100644--- a/tools/ci/cpu_stack_smoke.py+++ b/tools/ci/cpu_stack_smoke.py@@ -55,35 +55,75 @@ def wait_health(url: str, timeout: float = 180) -> None:raise RuntimeError(f"Container health did not become ready: {url}")-def config_models(config_url: str, token: str | None = None) -> set[str]:+def config_models(config_url: str, token: str) -> set[str]:request = urllib.request.Request(f"{config_url}/v1/configs/models")- if token is not None:- request.add_header("Authorization", f"Bearer {token}")+ request.add_header("Authorization", f"Bearer {token}")with urllib.request.urlopen(request, timeout=10) as response:return {model["model_id"] for model in json.load(response)["models"]}-def require_authenticated_catalog(config_url: str, token: str) -> set[str]:+def config_status(config_url: str, path: str, token: str | None = None, body: bytes | None = None) -> int:+ request = urllib.request.Request(f"{config_url}{path}", data=body, method="GET" if body is None else "POST")+ if token is not None:+ request.add_header("Authorization", f"Bearer {token}")try:- config_models(config_url)+ with urllib.request.urlopen(request, timeout=10) as response:+ return response.statusexcept urllib.error.HTTPError as error:- if error.code != 401:- raise RuntimeError(f"sie-config answered an unauthenticated catalog read with {error.code}") from error- else:- raise RuntimeError("sie-config served its catalog without the admin token")- catalog = config_models(config_url, token)+ return error.code+++def require_read_scoped_catalog(config_url: str, read_token: str) -> set[str]:+ write = b"sie_id: ci/read-token-probe\nprofiles:\n default:\n adapter_path: a:B\n max_batch_tokens: 1\n"+ checks = {+ "unauthenticated catalog read": (config_status(config_url, "/v1/configs/models"), 401),+ "read-token epoch": (config_status(config_url, "/v1/configs/epoch", read_token), 200),+ "read-token export": (config_status(config_url, "/v1/configs/export", read_token), 200),+ "read-token write": (config_status(config_url, "/v1/configs/models", read_token, write), 403),+ }+ wrong = {name: status for name, (status, expected) in checks.items() if status != expected}+ if wrong:+ raise RuntimeError(f"sie-config read-token scope is wrong: {wrong}")+ catalog = config_models(config_url, read_token)if not catalog:raise RuntimeError("sie-config returned an empty model catalog")+ print("sie-config serves the epoch, export and catalog to the read token and refuses its write.")return catalog+RECONCILE_RESULTS = (+ "export reconcile complete",+ "export reconcile partial",+ "export reconcile failed",+ "epoch poll failed",+)+++def latest_reconcile_result(logs: str) -> str | None:+ positions = {result: logs.rfind(result) for result in RECONCILE_RESULTS}+ latest = max(positions, key=positions.__getitem__)+ return latest if positions[latest] >= 0 else None+++def require_sidecar_export_reconcile(container: str, timeout: float = 150) -> None:+ deadline = time.monotonic() + timeout+ latest = None+ while time.monotonic() < deadline:+ latest = latest_reconcile_result(docker("logs", container, check=False))+ if latest == "export reconcile complete":+ print("Worker sidecar completed an export reconcile with the read token.")+ return+ time.sleep(2)+ raise RuntimeError(f"Worker sidecar did not complete an export reconcile with the read token; latest: {latest}")++def require_gateway_catalog(gateway_url: str, catalog: set[str]) -> None:with SIEClient(gateway_url, timeout_s=30) as client:listed = {model["name"] for model in client.list_models()}missing = sorted(catalog - listed)if missing:raise RuntimeError(f"Gateway is missing {len(missing)} sie-config catalog models, for example {missing[:5]}")- print(f"Gateway loaded the {len(catalog)}-model sie-config catalog through the admin token.")+ print(f"Gateway loaded the {len(catalog)}-model sie-config catalog through the read token.")def build_images(registry: str, revision: str) -> None:@@ -135,15 +175,16 @@ def main() -> None:try:start("nats", "nats:2.11.8-alpine", command=("-js",))- admin_token = secrets.token_urlsafe(32)+ read_token = secrets.token_urlsafe(32)config_env = {"SIE_NATS_URL": "nats://nats:4222","SIE_DEPLOYMENT_ENV": "production",- "SIE_ADMIN_TOKEN": admin_token,+ "SIE_ADMIN_TOKEN": secrets.token_urlsafe(32),+ "SIE_CONFIG_READ_TOKEN": read_token,}config_url = start("config", image("sie-config"), env=config_env, port=8080)wait_health(f"{config_url}/readyz")- catalog = require_authenticated_catalog(config_url, admin_token)+ catalog = require_read_scoped_catalog(config_url, read_token)worker_env = {"SIE_POOL": "default","SIE_BUNDLE": "fake",@@ -165,7 +206,7 @@ def main() -> None:gateway_env = {"SIE_NATS_URL": "nats://nats:4222","SIE_CONFIG_SERVICE_URL": "http://config:8080",- "SIE_ADMIN_TOKEN": admin_token,+ "SIE_CONFIG_SERVICE_TOKEN": read_token,"SIE_GATEWAY_HEALTH_MODE": "nats","SIE_GATEWAY_ENABLE_POOLS": "1","SIE_GATEWAY_REQUEST_TIMEOUT": "60",@@ -190,10 +231,11 @@ def main() -> None:"SIE_WORKER_ID": "cpu-smoke","SIE_GATEWAY_URL": "http://gateway:8080","SIE_CONFIG_SERVICE_URL": "http://config:8080",- "SIE_ADMIN_TOKEN": admin_token,+ "SIE_CONFIG_SERVICE_TOKEN": read_token,},)wait_health(f"{sidecar_url}/readyz")+ require_sidecar_export_reconcile(f"{network}-sidecar")wait_health(f"{gateway_url}/readyz")require_gateway_catalog(gateway_url, catalog)wait_for_api(gateway_url)diff --git a/tools/ci/tests/test_cpu_checks.py b/tools/ci/tests/test_cpu_checks.pyindex 0a7a9dcae..e3b74374a 100644--- a/tools/ci/tests/test_cpu_checks.py+++ b/tools/ci/tests/test_cpu_checks.py@@ -96,3 +96,61 @@ def test_cpu_stack_task_wraps_one_harness_and_docker_flag_delegates():assert "exec mise run cpu-stack" in test_taskassert 'ARGS+=("-m" "docker"' not in test_taskassert "test_docker_integration.py" not in test_task+++def test_read_scoped_catalog_requires_reads_and_a_refused_write(monkeypatch):+ statuses = {+ ("/v1/configs/models", None): 401,+ ("/v1/configs/epoch", "read"): 200,+ ("/v1/configs/export", "read"): 200,+ ("/v1/configs/models", "read"): 403,+ }+ monkeypatch.setattr(+ cpu_stack_smoke, "config_status", lambda _url, path, token=None, body=None: statuses[(path, token)]+ )+ monkeypatch.setattr(cpu_stack_smoke, "config_models", lambda _url, _token: {"model"})+ assert cpu_stack_smoke.require_read_scoped_catalog("http://config", "read") == {"model"}++ statuses[("/v1/configs/models", "read")] = 201+ with pytest.raises(RuntimeError, match="read-token write"):+ cpu_stack_smoke.require_read_scoped_catalog("http://config", "read")+++ ("logs", "latest"),+ [+ ("", None),+ ("worker-config: startup export reconcile complete", "export reconcile complete"),+ (+ "worker-config: startup export reconcile failed; will retry\nworker-config: export reconcile complete",+ "export reconcile complete",+ ),+ ("worker-config: startup export reconcile partial; will retry", "export reconcile partial"),+ (+ "worker-config: startup export reconcile complete\nworker-config: epoch poll failed",+ "epoch poll failed",+ ),+ ],+)+def test_latest_reconcile_result_reads_the_last_outcome(logs, latest):+ assert cpu_stack_smoke.latest_reconcile_result(logs) == latest+++def test_sidecar_export_reconcile_waits_for_a_complete_result(monkeypatch):+ logs = iter(+ [+ "worker-config: startup export reconcile failed; will retry",+ "worker-config: startup export reconcile failed; will retry\nworker-config: export reconcile complete",+ ]+ )+ monkeypatch.setattr(cpu_stack_smoke, "docker", lambda *args, check=True: next(logs))+ monkeypatch.setattr(cpu_stack_smoke.time, "sleep", lambda _seconds: None)+ cpu_stack_smoke.require_sidecar_export_reconcile("sidecar", timeout=5)+++def test_sidecar_export_reconcile_rejects_a_result_that_never_completes(monkeypatch):+ log = "worker-config: startup export reconcile partial; will retry"+ monkeypatch.setattr(cpu_stack_smoke, "docker", lambda *args, check=True: log)+ monkeypatch.setattr(cpu_stack_smoke.time, "sleep", lambda _seconds: None)+ with pytest.raises(RuntimeError, match="latest: export reconcile partial"):+ cpu_stack_smoke.require_sidecar_export_reconcile("sidecar", timeout=0.05)diff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.pyindex 39113304d..f4e0fbcbd 100644--- a/tools/ci/tests/test_helm_render.py+++ b/tools/ci/tests/test_helm_render.py@@ -23,11 +23,10 @@ AUTOSCALING_VALUES = {},}GENERATED_ADMIN_TOKEN_SECRET = "sie-sie-cluster-config-admin-token"-CONFIG_CLIENTS = (- "sie-sie-cluster-config/config",- "sie-sie-cluster-gateway/gateway",- "sie-sie-cluster-worker-l4-default/worker-sidecar",-)+GENERATED_READ_TOKEN_SECRET = "sie-sie-cluster-config-read-token"+CONFIG_SERVICE = "sie-sie-cluster-config/config"+GATEWAY = "sie-sie-cluster-gateway/gateway"+CONFIG_CONSUMERS = (GATEWAY, "sie-sie-cluster-worker-l4-default/worker-sidecar")L4_POOL = {"workers": {"pools": {"l4": {"enabled": True}}}}@@ -248,46 +247,221 @@ def container_env(docs: list[dict], workload: str, container: str) -> dict[str,return {env["name"]: env for env in spec.get("env", [])}-def admin_token_refs(docs: list[dict]) -> dict[str, dict]:- refs = {}+def env_entries(docs: list[dict], name: str) -> dict[str, dict]:+ entries = {}for doc in docs:if doc["kind"] not in {"Deployment", "StatefulSet"}:continuefor container in doc["spec"]["template"]["spec"]["containers"]:for env in container.get("env", []):- if env["name"] == "SIE_ADMIN_TOKEN":- refs[f"{doc['metadata']['name']}/{container['name']}"] = env["valueFrom"]["secretKeyRef"]- return refs+ if env["name"] == name:+ entries[f"{doc['metadata']['name']}/{container['name']}"] = env.get("valueFrom", {}).get(+ "secretKeyRef", env.get("value")+ )+ return entries++def token_secrets(docs: list[dict]) -> dict[str, dict]:+ return {+ doc["metadata"]["name"]: doc+ for doc in docs+ if doc["kind"] == "Secret" and doc["metadata"]["name"].endswith(("-admin-token", "-read-token"))+ }-def admin_token_secrets(docs: list[dict]) -> list[dict]:- return [doc for doc in docs if doc["kind"] == "Secret" and doc["metadata"]["name"].endswith("-admin-token")]++def secret_token(secret: dict, key: str) -> str:+ assert secret["metadata"]["annotations"] == {"helm.sh/resource-policy": "keep"}+ token = base64.b64decode(secret["data"][key]).decode()+ assert re.fullmatch(r"[A-Za-z0-9]{64}", token)+ return token+++def assert_token_scopes(docs: list[dict], admin: dict, read: dict | str) -> None:+ assert env_entries(docs, "SIE_ADMIN_TOKEN") == {CONFIG_SERVICE: admin}+ assert env_entries(docs, "SIE_CONFIG_READ_TOKEN") == {CONFIG_SERVICE: read}+ assert env_entries(docs, "SIE_CONFIG_SERVICE_TOKEN") == dict.fromkeys(CONFIG_CONSUMERS, read)+++GENERATED_ADMIN = {"name": GENERATED_ADMIN_TOKEN_SECRET, "key": "SIE_ADMIN_TOKEN"}+GENERATED_READ = {"name": GENERATED_READ_TOKEN_SECRET, "key": "SIE_CONFIG_READ_TOKEN"}+# Values as `helm upgrade --reuse-values` sees them from a release that predates+# these keys: null removes the chart default.+PREDATING_TOKEN_KEYS = {+ "config": {+ "auth": {+ "generateAdminToken": None,+ "readTokenSecretName": None,+ "readTokenSecretKey": None,+ "generateReadToken": None,+ }+ },+ "gateway": {"auth": {"adminTokenSecretName": None, "adminTokenSecretKey": None}},+}def test_chart_defaults_render_without_overrides(tmp_path: Path) -> None:docs = rendered_documents(tmp_path, {})gateway = container_env(docs, "sie-sie-cluster-gateway", "gateway")assert "SIE_PAYLOAD_STORE_URL" not in gateway- assert gateway["SIE_ADMIN_TOKEN"]["valueFrom"]["secretKeyRef"]["name"] == GENERATED_ADMIN_TOKEN_SECRET+ assert "SIE_ADMIN_TOKEN" not in gateway+ assert gateway["SIE_CONFIG_SERVICE_TOKEN"]["valueFrom"]["secretKeyRef"] == GENERATED_READassert container_env(docs, "sie-sie-cluster-config", "config")["SIE_DEPLOYMENT_ENV"]["value"] == "production"[email protected]("config", [{}, {"config": {"auth": {"generateAdminToken": None}}}])-def test_generated_admin_token_is_wired_to_every_config_client(tmp_path: Path, config: dict) -> None:- docs = rendered_documents(tmp_path, {**L4_POOL, **config})- (secret,) = admin_token_secrets(docs)- assert secret["metadata"]["name"] == GENERATED_ADMIN_TOKEN_SECRET- assert secret["metadata"]["annotations"] == {"helm.sh/resource-policy": "keep"}- assert re.fullmatch(r"[A-Za-z0-9]{64}", base64.b64decode(secret["data"]["SIE_ADMIN_TOKEN"]).decode())- expected = {"name": GENERATED_ADMIN_TOKEN_SECRET, "key": "SIE_ADMIN_TOKEN"}- assert admin_token_refs(docs) == dict.fromkeys(CONFIG_CLIENTS, expected)+EMPTY_GENERATION_FLAGS = {"config": {"auth": {"generateAdminToken": "", "generateReadToken": " "}}}++[email protected]("values", [{}, PREDATING_TOKEN_KEYS, EMPTY_GENERATION_FLAGS])+def test_generated_tokens_are_wired_by_scope(tmp_path: Path, values: dict) -> None:+ docs = rendered_documents(tmp_path, {**L4_POOL, **values})+ secrets = token_secrets(docs)+ assert set(secrets) == {GENERATED_ADMIN_TOKEN_SECRET, GENERATED_READ_TOKEN_SECRET}+ admin = secret_token(secrets[GENERATED_ADMIN_TOKEN_SECRET], "SIE_ADMIN_TOKEN")+ read = secret_token(secrets[GENERATED_READ_TOKEN_SECRET], "SIE_CONFIG_READ_TOKEN")+ assert admin != read+ assert_token_scopes(docs, GENERATED_ADMIN, GENERATED_READ)def test_operator_admin_token_secret_is_used_unchanged(tmp_path: Path) -> None:auth = {"adminTokenSecretName": "operator-admin", "adminTokenSecretKey": "token"}docs = rendered_documents(tmp_path, {**L4_POOL, "config": {"auth": auth}})- assert admin_token_secrets(docs) == []- assert admin_token_refs(docs) == dict.fromkeys(CONFIG_CLIENTS, {"name": "operator-admin", "key": "token"})+ assert set(token_secrets(docs)) == {GENERATED_READ_TOKEN_SECRET}+ assert_token_scopes(docs, {"name": "operator-admin", "key": "token"}, GENERATED_READ)+++def test_operator_read_token_secret_is_used_unchanged(tmp_path: Path) -> None:+ auth = {+ "adminTokenSecretName": "operator-admin",+ "adminTokenSecretKey": "token",+ "readTokenSecretName": "operator-read",+ "readTokenSecretKey": "read",+ "generateReadToken": False,+ }+ docs = rendered_documents(tmp_path, {**L4_POOL, "config": {"auth": auth}})+ assert token_secrets(docs) == {}+ assert_token_scopes(docs, {"name": "operator-admin", "key": "token"}, {"name": "operator-read", "key": "read"})+++def test_gateway_admin_token_is_wired_only_to_the_gateway(tmp_path: Path) -> None:+ values = {**L4_POOL, "gateway": {"auth": {"mode": "token", "adminTokenSecretName": "gateway-admin"}}}+ docs = rendered_documents(tmp_path, values)+ assert env_entries(docs, "SIE_ADMIN_TOKEN") == {+ CONFIG_SERVICE: GENERATED_ADMIN,+ GATEWAY: {"name": "gateway-admin", "key": "SIE_ADMIN_TOKEN"},+ }+ assert env_entries(docs, "SIE_CONFIG_SERVICE_TOKEN") == dict.fromkeys(CONFIG_CONSUMERS, GENERATED_READ)+++def test_gateway_without_sie_config_sends_no_config_credential(tmp_path: Path) -> None:+ values = {+ "config": {"enabled": False},+ "gateway": {"embeddedConfigs": {"enabled": True}, "auth": {"adminTokenSecretName": "gateway-admin"}},+ }+ gateway = container_env(rendered_documents(tmp_path, values), "sie-sie-cluster-gateway", "gateway")+ assert "SIE_CONFIG_SERVICE_URL" not in gateway+ assert gateway["SIE_CONFIG_SERVICE_TOKEN"] == {"name": "SIE_CONFIG_SERVICE_TOKEN", "value": ""}+ assert gateway["SIE_ADMIN_TOKEN"]["valueFrom"]["secretKeyRef"] == {+ "name": "gateway-admin",+ "key": "SIE_ADMIN_TOKEN",+ }+++ ("values", "error"),+ [+ (+ {+ "config": {+ "auth": {+ "readTokenSecretName": GENERATED_ADMIN_TOKEN_SECRET,+ "readTokenSecretKey": "SIE_ADMIN_TOKEN",+ }+ }+ },+ "config.auth.readTokenSecretName and readTokenSecretKey point at the sie-config admin token",+ ),+ (+ {+ "config": {+ "auth": {+ "adminTokenSecretName": "shared",+ "adminTokenSecretKey": "token",+ "readTokenSecretName": "shared",+ "readTokenSecretKey": "token",+ }+ }+ },+ "config.auth.readTokenSecretName and readTokenSecretKey point at the sie-config admin token",+ ),+ (+ {"gateway": {"auth": {"adminTokenSecretName": GENERATED_ADMIN_TOKEN_SECRET}}},+ "gateway.auth.adminTokenSecretName and adminTokenSecretKey point at the sie-config admin token",+ ),+ (+ {+ "gateway": {+ "auth": {+ "adminTokenSecretName": GENERATED_READ_TOKEN_SECRET,+ "adminTokenSecretKey": "SIE_CONFIG_READ_TOKEN",+ }+ }+ },+ "gateway.auth.adminTokenSecretName and adminTokenSecretKey point at the sie-config read token",+ ),+ ],+)+def test_shared_token_secrets_fail_the_render(tmp_path: Path, values: dict, error: str) -> None:+ result = render_chart(tmp_path, {**L4_POOL, **values})+ assert result.returncode != 0+ assert error in result.stderr+++def test_tokens_in_one_secret_under_different_keys_render(tmp_path: Path) -> None:+ auth = {+ "adminTokenSecretName": "sie-tokens",+ "adminTokenSecretKey": "admin",+ "readTokenSecretName": "sie-tokens",+ "readTokenSecretKey": "read",+ }+ values = {**L4_POOL, "config": {"auth": auth}, "gateway": {"auth": {"adminTokenSecretName": "sie-tokens"}}}+ docs = rendered_documents(tmp_path, values)+ assert env_entries(docs, "SIE_ADMIN_TOKEN") == {+ CONFIG_SERVICE: {"name": "sie-tokens", "key": "admin"},+ GATEWAY: {"name": "sie-tokens", "key": "SIE_ADMIN_TOKEN"},+ }+ read = {"name": "sie-tokens", "key": "read"}+ assert env_entries(docs, "SIE_CONFIG_READ_TOKEN") == {CONFIG_SERVICE: read}+ assert env_entries(docs, "SIE_CONFIG_SERVICE_TOKEN") == dict.fromkeys(CONFIG_CONSUMERS, read)++[email protected]("name", ["SIE_ADMIN_TOKEN", "SIE_CONFIG_SERVICE_TOKEN"])+ ("path", "values"),+ [+ ("gateway.extraEnv", lambda entry: {"gateway": {"extraEnv": [entry]}}),+ (+ "workers.common.workerSidecar.extraEnv",+ lambda entry: {"workers": {"common": {"workerSidecar": {"extraEnv": [entry]}}}},+ ),+ ],+)+def test_config_credentials_cannot_be_overridden_through_extra_env(+ tmp_path: Path, name: str, path: str, values+) -> None:+ rendered = values({"name": name, "value": "override"})+ result = render_chart(+ tmp_path, {**L4_POOL, **rendered, "workers": {**L4_POOL["workers"], **rendered.get("workers", {})}}+ )+ assert result.returncode != 0+ assert f"{path} must not override chart-owned variable {name}" in result.stderr+++def test_production_without_an_admin_token_names_the_read_only_effect(tmp_path: Path) -> None:+ auth = {"generateAdminToken": False, "readTokenSecretName": "operator-read"}+ result = render_chart(tmp_path, {"config": {"auth": auth}})+ assert result.returncode != 0+ assert "so it would refuse every config write and serve only reads that present the read token" in result.stderr+ assert "refuse every /v1/configs request" not in result.stderr@pytest.mark.parametrize("key", [None, "", " "])@@ -297,6 +471,35 @@ def test_empty_admin_token_key_fails_the_render(tmp_path: Path, key: str | None)assert "config.auth.adminTokenSecretKey is empty" in result.stderr+ ("values", "error"),+ [+ ({"config": {"auth": {"readTokenSecretKey": ""}}}, "config.auth.readTokenSecretKey is empty"),+ ({"config": {"auth": {"readTokenSecretKey": " "}}}, "config.auth.readTokenSecretKey is empty"),+ (+ {"gateway": {"auth": {"adminTokenSecretName": "gateway-admin", "adminTokenSecretKey": ""}}},+ "gateway.auth.adminTokenSecretKey is empty",+ ),+ (+ {"gateway": {"auth": {"adminTokenSecretName": "gateway-admin", "adminTokenSecretKey": " "}}},+ "gateway.auth.adminTokenSecretKey is empty",+ ),+ ],+)+def test_empty_token_key_fails_the_render(tmp_path: Path, values: dict, error: str) -> None:+ result = render_chart(tmp_path, {**L4_POOL, **values})+ assert result.returncode != 0+ assert error in result.stderr++[email protected]("disabled", [False, "false", " False "])[email protected]("admin", [{}, {"adminTokenSecretName": "operator-admin"}])+def test_admin_token_without_a_read_token_fails_the_render(tmp_path: Path, admin: dict, disabled: object) -> None:+ result = render_chart(tmp_path, {**L4_POOL, "config": {"auth": {**admin, "generateReadToken": disabled}}})+ assert result.returncode != 0+ assert "sie-config has an admin token but no read token" in result.stderr++@pytest.mark.parametrize("telemetry", [{}, {"deploymentEnv": "production"}, {"deploymentEnv": " Prod "}])def test_production_config_service_without_a_token_fails_the_render(tmp_path: Path, telemetry: dict) -> None:result = render_chart(tmp_path, {"config": {"auth": {"generateAdminToken": False}}, "telemetry": telemetry})@@ -322,20 +525,23 @@ def test_non_production_config_service_may_opt_out_of_the_token(tmp_path: Path,"telemetry": {"deploymentEnv": deployment_env},}docs = rendered_documents(tmp_path, values)- assert admin_token_secrets(docs) == []- assert admin_token_refs(docs) == {}+ assert token_secrets(docs) == {}+ assert env_entries(docs, "SIE_ADMIN_TOKEN") == {}+ assert env_entries(docs, "SIE_CONFIG_READ_TOKEN") == {}+ assert env_entries(docs, "SIE_CONFIG_SERVICE_TOKEN") == dict.fromkeys(CONFIG_CONSUMERS, "")[email protected]("setting", ["admin", "read"])@pytest.mark.parametrize(("token", "error"),[- ("", "Secret admin exists but has no SIE_ADMIN_TOKEN key"),- ("a" * 31, "Secret admin holds a SIE_ADMIN_TOKEN value shorter than 32 characters"),+ ("", "Secret generated exists but has no TOKEN_KEY key. If config.auth.{setting}TokenSecretKey was renamed"),+ ("a" * 31, "Secret generated holds a TOKEN_KEY value shorter than 32 characters"),("a" * 32, None),],)-def test_reused_admin_token_must_exist_and_have_at_least_32_characters(- tmp_path: Path, token: str, error: str | None+def test_reused_token_must_exist_and_have_at_least_32_characters(+ tmp_path: Path, setting: str, token: str, error: str | None) -> None:chart = tmp_path / "helper-check"(chart / "templates").mkdir(parents=True)@@ -343,8 +549,10 @@ def test_reused_admin_token_must_exist_and_have_at_least_32_characters(shutil.copy(ROOT / helm.CHART_DIR / "templates" / "_helpers.tpl", chart / "templates" / "_helpers.tpl")data = base64.b64encode(token.encode()).decode()(chart / "templates" / "check.yaml").write_text(- '{{- include "sie-cluster.config.validateReusedAdminToken" '- f'(dict "name" "admin" "key" "SIE_ADMIN_TOKEN" "data" "{data}") }}}}\n',+ '{{- include "sie-cluster.config.validateReusedToken" '+ f'(dict "name" "generated" "key" "TOKEN_KEY" "data" "{data}" '+ f'"keySetting" "config.auth.{setting}TokenSecretKey" '+ f'"nameSetting" "config.auth.{setting}TokenSecretName") }}}}\n',encoding="utf-8",)result = subprocess.run(@@ -358,4 +566,4 @@ def test_reused_admin_token_must_exist_and_have_at_least_32_characters(assert result.returncode == 0, result.stderrelse:assert result.returncode != 0- assert error in result.stderr+ assert error.format(setting=setting) in result.stderr