Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(helm)!: authenticate every NATS connection with per-component users (#421)
Krisztian Gajdar60f30ab4a6f1
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 1f098baa7..11d9e5011 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -764,6 +764,9 @@ helm install sie deploy/helm/sie-cluster \-f deploy/helm/sie-cluster/values-ha.yaml```+The NATS members authenticate their routes to each other as `sie-route` (see+"NATS authentication").+It does not make `sie-config` redundant; that service stays at one replica bytemplate design until the chart provides leader election. And because a livestream's storage type cannot be changed, apply it to a fresh install or convert@@ -859,6 +862,160 @@ The comparison spans the gateway and worker clocks, so keep the nodessynchronised (for example with NTP). Watch`sie_worker_work_item_deadline_exceeded_total` before enabling enforcement.+### NATS authentication++sie-config, the gateway, and the worker sidecars connect to NATS as separate+users. The bundled server refuses anonymous connections and limits each user+to the subjects that component uses:++| User | Publish | Subscribe |+| --- | --- | --- |+| `sie-config` | `sie.config.models.>` | nothing |+| `sie-gateway` | `sie.work.>`, `sie.dlq.>`, `cancel.>`, `work_cancel.>`, `batch_cancel.>`, `$JS.API.STREAM.INFO.*`, `$JS.API.STREAM.CREATE.*`, `$JS.API.STREAM.UPDATE.*`, `$JS.API.CONSUMER.INFO.*.*` | `sie.config.models._all`, `sie.health.>`, `_INBOX.>`, `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` |+| `sie-worker` | `_INBOX.>` (results), `sie.health.>`, `$JS.ACK.>`, `$JS.API.STREAM.INFO.*`, `$JS.API.STREAM.CREATE.*`, `$JS.API.STREAM.UPDATE.*`, `$JS.API.CONSUMER.LIST.*`, `$JS.API.CONSUMER.INFO.*.*`, `$JS.API.CONSUMER.CREATE.*.>`, `$JS.API.CONSUMER.DELETE.*.*`, `$JS.API.CONSUMER.MSG.NEXT.*.*` | `sie.config.models.*`, `cancel.>`, `work_cancel.>`, `batch_cancel.>`, `_INBOX_WORKER.>` |+| `sie-route` | Routes between NATS members, when `nats.config.cluster.enabled=true` | |++- Only `sie-config` can publish on `sie.config.models.>`, and only the+ gateway can publish work and cancel signals.+- A user that may manage JetStream streams or consumers can make the server+ itself deliver stored messages to any subject: through a stream's republish+ setting, a consumer's delivery subject, or the reply subject of a pull or+ direct-get request. Subject permissions do not apply to those deliveries.+ Each of them carries a reply subject or a `Nats-` header, and sie-config and+ the gateway send neither on these subjects. The gateway and the worker+ sidecars therefore drop config notifications and cancel signals that carry+ either, and the gateway drops max-deliveries advisories that do.+- The worker sidecars drop work that carries a `Nats-` header other than+ `Nats-Msg-Id`, which the gateway sets for deduplication. This rejects work+ that a stream republish or a stream source copied into a work stream.+- The worker sidecar receives its own JetStream replies and pull deliveries+ under the inbox prefix `_INBOX_WORKER`. The worker user can publish results+ to the gateway's `_INBOX` subjects but cannot subscribe to them.+- In a worker pod, only the sidecar container gets the worker credentials. The+ container that runs model code has none.+- Only gateway pods mount a Kubernetes API token. Worker, sie-config, and+ mcp-edge pods set `automountServiceAccountToken: false`, and none of them+ calls the Kubernetes API. They keep the `sie-server` ServiceAccount, so+ cloud workload identity (EKS IRSA and Pod Identity, GKE and AKS workload+ identity, ACK RRSA), which projects its own token, keeps working. The+ gateway's pool Role covers every ConfigMap in the namespace, including the+ NATS server configuration `<release>-nats-config`, because pool ConfigMaps+ are named at runtime. The gateway pod can therefore change the NATS users,+ and is trusted with the bus.+- The NATS monitoring port (8222) stays unauthenticated. It shows connection+ and subscription metadata, including user names, but no message contents+ or passwords. The chart ships no NetworkPolicy for the NATS pods, so+ restrict that port with one where that matters. The client (4222) and+ cluster route (6222) ports require credentials.+- `workers.networkPolicy` restricts only ingress to the worker pods. The+ worker sidecars open their NATS connections outward, so the policy does not+ affect NATS.+- The chart does not configure TLS on NATS. Passwords and messages cross the+ pod network in plaintext.+- nats-box and the NATS `helm test` pod are disabled, because they would+ connect without credentials.++**What the worker user can still do.** All workers share the `sie-worker`+user, because the subject names do not separate one worker from another. It+keeps JetStream stream and consumer management, because the sidecars create+their own direct-dispatch streams and repair the pool streams' settings. The+server does not check a stream's subjects against the creating user's+subscribe permissions. Anyone who holds the worker credentials, such as a+compromised sidecar process, can therefore:++- read gateway results and JetStream API replies, by creating a stream that+ captures `_INBOX.>` and reading it through a consumer. A stream created with+ `no_ack` can capture `$JS.API.>` and `$JS.ACK.>` the same way.+- read, settle, and redeliver work queued for any pool, and create, change,+ or delete any pool's durable consumers.+- change any stream's configuration. Lowering `max_msgs` drops queued work,+ and sealing a stream makes it refuse new work until the stream is deleted,+ which no user in the matrix above may do.+- add work to any pool without a `Nats-` header, through a subject transform+ on the pool stream. The header check above does not catch this.+- send heartbeats in the name of other workers.++Removing these rights needs streams that only the gateway manages, or a+separate NATS account per worker. Both are planned follow-ups.++**Recovering a sealed or damaged stream.** With the default memory storage,+restart NATS (`kubectl rollout restart statefulset/<release>-nats`). The+gateway and the workers create the streams again, and queued work is lost.+With file storage no user in the matrix may delete a stream. Upgrade once with+`--set nats.auth.allowAnonymous=true --set nats.natsBox.enabled=true`, run+`nats stream rm <stream> -f` in the nats-box pod, and upgrade again with+`--set nats.auth.allowAnonymous=false --set nats.natsBox.enabled=false`.++**Passwords.** The chart generates one Secret per user,+`<release>-nats-auth-config`, `-gateway`, and `-worker`, plus `-route` when the+NATS cluster is enabled. Each holds a random 48-character `password` of+letters and digits that starts with a letter. On upgrade the chart reads the+existing Secret with `lookup` and keeps its password. The render fails if a+kept Secret has no `password` key, or a password shorter than 32 characters,+with characters other than letters and digits, or starting with a digit. The+Secrets carry `helm.sh/resource-policy: keep`. The NATS server reads the+passwords from its environment, and each client container gets+`SIE_NATS_USER` and `SIE_NATS_PASSWORD`.++To manage a password yourself, set `nats.auth.existingSecrets.<config|gateway|worker|route>`+to a Secret with a `password` key. For the bundled server it must be letters+and digits and start with a letter: the server parses it as a configuration+value, where a leading digit reads as a number, and embeds it in route URLs.++Renderers without cluster access, such as `helm template` and many GitOps+controllers, cannot read the existing Secrets and generate new passwords on+every render. Use `existingSecrets` with them, or on Argo CD set+`ignoreDifferences` on the Secrets' `/data` together with the+`RespectIgnoreDifferences=true` sync option. Do not commit `helm template`+output, which contains the passwords.++**Rotating a password.** Delete the generated Secret (or change your own) and+run `helm upgrade`. Then restart the NATS StatefulSet, which reads passwords+only at start, and the workloads that use that user. They cannot connect until+both sides have the new password. Helm keeps every rendered Secret in its+release history, so a `helm rollback` to an earlier revision brings back the+earlier password, and anyone who can read Secrets in the namespace can read the+history.++**Upgrading an existing release.** Authentication is on by default, so the+upgrade changes the NATS server, sie-config, the gateway, and the workers+together:++- The NATS pod restarts. With the default memory-backed work queues, queued+ and in-flight work is lost, as on any NATS restart (see "Work-queue+ durability").+- A gateway, sie-config, or worker pod that has not been replaced yet has no+ credentials, and the server refuses it. Requests can fail with `503`, and+ workers that have not restarted take no work until they do.++To avoid that gap, upgrade in two steps. First upgrade with+`--set nats.auth.allowAnonymous=true`: the server then also accepts anonymous+connections, with unrestricted permissions. Once every pod has restarted,+upgrade again with `--set nats.auth.allowAnonymous=false`. Set it explicitly:+`--reuse-values` and `--reset-then-reuse-values` both keep the value from the+first step. The second step only changes the NATS configuration, which the+server reloads without restarting. `helm status` prints a warning while+anonymous access is on.++`helm upgrade --reuse-values` reuses the old release's NATS sub-chart values,+which lack the chart's server wiring, so the render fails. Upgrade with+`--reset-then-reuse-values` (Helm 3.14 or later) or pass your values with `-f`.+The wiring lives in the `sieNatsAuth` keys under `nats.config.merge`,+`nats.config.cluster.merge`, and `nats.container.env`. Keep them when you add+your own settings next to them.++**Opting out.** `nats.auth.enabled=false` renders NATS without users and+connects the clients without credentials, as before. Use it only where the+network already keeps other workloads away from NATS.++**External NATS** (`nats.install=false`). The chart cannot configure your+server. With `nats.auth.enabled=true`, set `nats.auth.existingSecrets.config`,+`.gateway`, and `.worker`, and create the users `sie-config`, `sie-gateway`,+and `sie-worker` with the permissions above. If your server needs no+credentials, set `nats.auth.enabled=false`. The clients read credentials only+from `SIE_NATS_USER` and `SIE_NATS_PASSWORD`. They remove any credentials in+`nats.url` before connecting.+### Upgrading from the legacy single-bundle pool schemaReleases up to and including 0.4.x used a flat schema where each pooldiff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txtindex 009018c01..6ff0fe3a4 100644--- a/deploy/helm/sie-cluster/templates/NOTES.txt+++ b/deploy/helm/sie-cluster/templates/NOTES.txt@@ -1,4 +1,5 @@{{- include "sie-cluster.validateNats" . -}}+{{- include "sie-cluster.nats.validateAuth" . -}}{{- include "sie-cluster.validateTls" . -}}{{- include "sie-cluster.validateKedaWatchNamespace" . -}}{{- include "sie-cluster.validateBundledTelemetryBackends" . -}}@@ -7,6 +8,25 @@SIE Cluster {{ .Chart.Version }} deployed to namespace {{ include "sie-cluster.namespace" . }}.Gateway: http://{{ include "sie-cluster.gateway.serviceName" . }}.{{ include "sie-cluster.namespace" . }}.svc:{{ .Values.gateway.service.port }}+{{- if include "sie-cluster.nats.authEnabled" . }}+{{- if and .Values.nats.install (dig "auth" "allowAnonymous" false .Values.nats) }}+NATS: ANONYMOUS ACCESS IS ON++*****************************************************************************************************+WARNING: nats.auth.allowAnonymous=true. The NATS server accepts anonymous connections with+unrestricted permissions: any pod that can reach NATS can read queued work and publish model+configuration to the gateway and the workers. This setting is only for the first step of the+upgrade. Once every pod has restarted, run helm upgrade again with+--set nats.auth.allowAnonymous=false. --reuse-values and --reset-then-reuse-values keep it on.+*****************************************************************************************************+{{- else }}+NATS: authenticated; sie-config, the gateway, and the worker sidecars each connect as their own user.+{{- end }}+{{- else if .Values.nats.enabled }}++WARNING: NATS authentication is off (nats.auth.enabled=false). Any pod that can reach NATS can read+queued work and publish model configuration to the gateway and the workers.+{{- end }}{{- 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 -ddiff --git a/deploy/helm/sie-cluster/templates/_nats-auth.tpl b/deploy/helm/sie-cluster/templates/_nats-auth.tplnew file mode 100644index 000000000..7efb24876--- /dev/null+++ b/deploy/helm/sie-cluster/templates/_nats-auth.tpl@@ -0,0 +1,261 @@+{{/*+NATS authentication (nats.auth).++sie-config, the gateway and the worker sidecars each connect as their own NATS+user, and the bundled server limits each user to the subjects that component+uses. Passwords live in one Secret per component, holding a `password` key.+The same names are computed here and, through `$tplYamlSpread` in the+`nats:` values, inside the NATS sub-chart, so both sides must build them from+values both can see: nats.auth and the release name.++The "sie-cluster.nats.server.*" templates run in the NATS sub-chart's context,+where .Values is the `nats:` block (so nats.auth is .Values.auth).+*/}}++{{- define "sie-cluster.nats.authComponents" -}}+{{- toJson (list "config" "gateway" "worker") -}}+{{- end }}++{{/*+"true" when NATS connections authenticate: nats.enabled, and nats.auth.enabled+is not false. An absent key counts as true, so `helm upgrade --reuse-values`+from a release that predates it keeps the default.+*/}}+{{- define "sie-cluster.nats.authEnabled" -}}+{{- if and .Values.nats.enabled (dig "auth" "enabled" true .Values.nats) -}}+true+{{- end -}}+{{- end }}++{{/*+NATS user of a component. Args: component name.+*/}}+{{- define "sie-cluster.nats.authUser" -}}+{{- printf "sie-%s" . -}}+{{- end }}++{{/*+Secret holding a component's NATS password: nats.auth.existingSecrets.<component>+when set, otherwise the chart-generated "<release>-nats-auth-<component>".+Args (dict): auth (nats.auth), release (release name), component.+*/}}+{{- define "sie-cluster.nats.authSecretName" -}}+{{- $existing := dig "existingSecrets" .component "" (.auth | default dict) -}}+{{- if $existing -}}+{{- $existing -}}+{{- else -}}+{{- printf "%s-nats-auth-%s" .release .component -}}+{{- end -}}+{{- end }}++{{/*+SIE_NATS_USER / SIE_NATS_PASSWORD for a client container, or nothing when NATS+authentication is off. Args (dict): root (top-level context), component.+*/}}+{{- define "sie-cluster.nats.clientAuthEnv" -}}+{{- if include "sie-cluster.nats.authEnabled" .root -}}+- name: SIE_NATS_USER+ value: {{ include "sie-cluster.nats.authUser" .component | quote }}+- name: SIE_NATS_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ include "sie-cluster.nats.authSecretName" (dict "auth" .root.Values.nats.auth "release" .root.Release.Name "component" .component) }}+ key: password+{{- end -}}+{{- end }}++{{/*+Fail when a reused generated NATS password Secret has no usable password,+instead of replacing a password that running pods hold. The server parses the+password as a configuration value and embeds it in cluster route URLs, so it+must be letters and digits and start with a letter (a leading digit parses as+a number). Args (dict): name (Secret), data (base64 value, empty when the key+is missing).+*/}}+{{- define "sie-cluster.nats.validateReusedPassword" -}}+{{- if not .data -}}+{{- fail (printf "Secret %s exists but has no password key. If it was created by hand, set nats.auth.existingSecrets to it so the chart uses it unchanged. Otherwise delete the Secret so the chart generates a new password, then restart NATS, sie-config, the gateway, and the workers." .name) -}}+{{- end -}}+{{- $password := b64dec .data -}}+{{- if lt (len $password) 32 -}}+{{- fail (printf "Secret %s holds a password shorter than 32 characters. Replace it with a random value of at least 32 letters and digits, or delete the Secret so the chart generates a new one, then restart NATS, sie-config, the gateway, and the workers." .name) -}}+{{- end -}}+{{- if not (regexMatch "^[A-Za-z][A-Za-z0-9]*$" $password) -}}+{{- fail (printf "Secret %s holds a password that is not letters and digits starting with a letter. The NATS server parses it as a configuration value and embeds it in route URLs, where other characters or a leading digit break parsing. Replace it, or delete the Secret so the chart generates a new one." .name) -}}+{{- end -}}+{{- end }}++{{/*+Validate the NATS authentication settings.++For the bundled server, the NATS sub-chart values must still contain the+chart's wiring (the `sieNatsAuth` keys). `helm upgrade --reuse-values` from a+release that predates NATS authentication replaces the chart's default values+with the old ones, which would leave the server without authentication while+the clients send credentials. Fail instead.++For an external server, every client that connects needs an operator Secret.+*/}}+{{- define "sie-cluster.nats.validateAuth" -}}+{{- if include "sie-cluster.nats.authEnabled" . -}}+{{- $auth := .Values.nats.auth | default dict -}}+{{- if .Values.nats.install -}}+{{- $wired := and (hasKey (dig "config" "merge" (dict) .Values.nats) "sieNatsAuth") (hasKey (dig "container" "env" (dict) .Values.nats) "sieNatsAuth") -}}+{{- if and $wired (dig "config" "cluster" "enabled" false .Values.nats) -}}+{{- $wired = hasKey (dig "config" "cluster" "merge" (dict) .Values.nats) "sieNatsAuth" -}}+{{- end -}}+{{- if not $wired -}}+{{- fail "NATS authentication is on (nats.auth.enabled), but the NATS values of this release lack the chart's server wiring (the sieNatsAuth keys under nats.config.merge, nats.config.cluster.merge, and nats.container.env). This happens with `helm upgrade --reuse-values` from a release that predates NATS authentication. Upgrade with --reset-then-reuse-values (Helm 3.14 or later) or pass your values with -f instead, and do not remove those keys. To keep NATS unauthenticated, set nats.auth.enabled=false." -}}+{{- end -}}+{{- else -}}+{{- if dig "allowAnonymous" false $auth -}}+{{- fail "nats.auth.allowAnonymous applies only to the bundled NATS server (nats.install=true). Configure anonymous access on the external server instead." -}}+{{- end -}}+{{- $needed := list "gateway" -}}+{{- if .Values.config.enabled -}}+{{- $needed = append $needed "config" -}}+{{- end -}}+{{- if .Values.workers.common.workerSidecar.enabled -}}+{{- $needed = append $needed "worker" -}}+{{- end -}}+{{- range $component := $needed -}}+{{- if not (dig "existingSecrets" $component "" $auth) -}}+{{- fail (printf "nats.install=false with nats.auth.enabled=true needs nats.auth.existingSecrets.%s: a Secret holding the %s NATS password under the key password, for the user %s on the external server. Set nats.auth.enabled=false if the external server does not require authentication." $component $component (include "sie-cluster.nats.authUser" $component)) -}}+{{- end -}}+{{- end -}}+{{- end -}}+{{- end -}}+{{- end }}++{{/*+NATS container env for the bundled server (NATS sub-chart context): one+password per user, read from the component Secrets, and, when clustered, the+route password and the route URLs that embed it. Kubernetes expands+$(SIE_NATS_AUTH_ROUTE_PASSWORD) because the sub-chart renders env vars in+name order and that name sorts first.+*/}}+{{- define "sie-cluster.nats.server.env" -}}+{{- $auth := .Values.auth | default dict -}}+{{- if and .Values.enabled (dig "enabled" true $auth) -}}+{{- $components := include "sie-cluster.nats.authComponents" . | fromJsonArray -}}+{{- if .Values.config.cluster.enabled -}}+{{- $components = append $components "route" -}}+{{- end -}}+{{- range $component := $components }}+{{ printf "SIE_NATS_AUTH_%s_PASSWORD" (upper $component) }}:+ valueFrom:+ secretKeyRef:+ name: {{ include "sie-cluster.nats.authSecretName" (dict "auth" $auth "release" $.Release.Name "component" $component) }}+ key: password+{{- end }}+{{- if .Values.config.cluster.enabled }}+SIE_NATS_ROUTES: {{ include "sie-cluster.nats.server.routeUrls" . | quote }}+{{- end }}+{{- end -}}+{{- end }}++{{/*+Cluster route URLs with the route user's credentials, matching the hosts the+NATS sub-chart renders in files/config/cluster.yaml.+*/}}+{{- define "sie-cluster.nats.server.routeUrls" -}}+{{- $urls := list -}}+{{- with .Values.config.cluster -}}+{{- $domain := $.Values.headlessService.name -}}+{{- if .routeURLs.useFQDN -}}+{{- $domain = printf "%s.%s.svc.%s" $domain (include "nats.namespace" $) .routeURLs.k8sClusterDomain -}}+{{- end -}}+{{- $proto := ternary "tls" "nats" .tls.enabled -}}+{{- $port := int .port -}}+{{- range $i, $_ := until (int .replicas) -}}+{{- $urls = append $urls (printf "%s://%s:$(SIE_NATS_AUTH_ROUTE_PASSWORD)@%s-%d.%s:%d" $proto (include "sie-cluster.nats.authUser" "route") $.Values.statefulSet.name $i $domain $port) -}}+{{- end -}}+{{- end -}}+{{- printf "[%s]" (join "," $urls) -}}+{{- end }}++{{/*+Top-level NATS server configuration (NATS sub-chart context): the users and+their permissions. Subjects are listed in the chart README ("NATS+authentication"). Passwords are environment references, unquoted by the+sub-chart's << >> rule.+*/}}+{{- define "sie-cluster.nats.server.configMerge" -}}+{{- $auth := .Values.auth | default dict -}}+{{- if and .Values.enabled (dig "enabled" true $auth) -}}+authorization:+ users:+ - user: {{ include "sie-cluster.nats.authUser" "config" }}+ password: "<< $SIE_NATS_AUTH_CONFIG_PASSWORD >>"+ permissions:+ publish:+ allow:+ - "sie.config.models.>"+ subscribe:+ deny:+ - ">"+ - user: {{ include "sie-cluster.nats.authUser" "gateway" }}+ password: "<< $SIE_NATS_AUTH_GATEWAY_PASSWORD >>"+ permissions:+ publish:+ allow:+ - "sie.work.>"+ - "sie.dlq.>"+ - "cancel.>"+ - "work_cancel.>"+ - "batch_cancel.>"+ - "$JS.API.STREAM.INFO.*"+ - "$JS.API.STREAM.CREATE.*"+ - "$JS.API.STREAM.UPDATE.*"+ - "$JS.API.CONSUMER.INFO.*.*"+ subscribe:+ allow:+ - "sie.config.models._all"+ - "sie.health.>"+ - "_INBOX.>"+ - "$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>"+ - user: {{ include "sie-cluster.nats.authUser" "worker" }}+ password: "<< $SIE_NATS_AUTH_WORKER_PASSWORD >>"+ permissions:+ publish:+ allow:+ - "_INBOX.>"+ - "sie.health.>"+ - "$JS.ACK.>"+ - "$JS.API.STREAM.INFO.*"+ - "$JS.API.STREAM.CREATE.*"+ - "$JS.API.STREAM.UPDATE.*"+ - "$JS.API.CONSUMER.LIST.*"+ - "$JS.API.CONSUMER.INFO.*.*"+ - "$JS.API.CONSUMER.CREATE.*.>"+ - "$JS.API.CONSUMER.DELETE.*.*"+ - "$JS.API.CONSUMER.MSG.NEXT.*.*"+ subscribe:+ allow:+ - "sie.config.models.*"+ - "cancel.>"+ - "work_cancel.>"+ - "batch_cancel.>"+ - "_INBOX_WORKER.>"+ {{- if dig "allowAnonymous" false $auth }}+ - user: sie-anonymous+ {{- end }}+{{- if dig "allowAnonymous" false $auth }}+no_auth_user: sie-anonymous+{{- end }}+{{- end -}}+{{- end }}++{{/*+Cluster block additions (NATS sub-chart context): routes authenticate as the+route user, and the route URLs carry its password.+*/}}+{{- define "sie-cluster.nats.server.clusterMerge" -}}+{{- $auth := .Values.auth | default dict -}}+{{- if and .Values.enabled (dig "enabled" true $auth) .Values.config.cluster.enabled -}}+authorization:+ user: {{ include "sie-cluster.nats.authUser" "route" }}+ password: "<< $SIE_NATS_AUTH_ROUTE_PASSWORD >>"+routes: "<< $SIE_NATS_ROUTES >>"+{{- end -}}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/config-deployment.yaml b/deploy/helm/sie-cluster/templates/config-deployment.yamlindex 796aefa4d..6a9323bb1 100644--- a/deploy/helm/sie-cluster/templates/config-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/config-deployment.yaml@@ -64,6 +64,7 @@ spec:{{- toYaml . | nindent 8 }}{{- end }}serviceAccountName: {{ include "sie-cluster.serviceAccountName" . }}+ automountServiceAccountToken: falsecontainers:- name: configimage: {{ include "sie-cluster.config.image" . }}@@ -111,6 +112,7 @@ spec:{{- if .Values.nats.enabled }}- name: SIE_NATS_URLvalue: {{ .Values.nats.url | default (printf "nats://%s-nats:4222" .Release.Name) | quote }}+ {{- include "sie-cluster.nats.clientAuthEnv" (dict "root" . "component" "config") | nindent 12 }}{{- end }}{{- if .Values.config.configStore.enabled }}- name: SIE_CONFIG_STORE_DIRdiff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex 8f30ab4d8..c8ccfc63e 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -34,6 +34,8 @@"SIE_GATEWAY_STATIC_QUEUE_POOLS""SIE_ADMIN_TOKEN""SIE_CONFIG_SERVICE_TOKEN"+ "SIE_NATS_PASSWORD"+ "SIE_NATS_USER""SIE_STREAM_MAX_AGE_S""SIE_STREAM_REPLICAS""SIE_STREAM_STORAGE") -}}@@ -279,6 +281,7 @@ spec:{{- if .Values.nats.enabled }}- name: SIE_NATS_URLvalue: {{ .Values.nats.url | default (printf "nats://%s-nats:4222" .Release.Name) | quote }}+ {{- include "sie-cluster.nats.clientAuthEnv" (dict "root" . "component" "gateway") | nindent 12 }}{{- if .Values.config.enabled }}# Allowlist of `producer_id` values trusted on `sie.config.models._all`.# `sie-config` publishes its POD_NAME, which is the Deployment namediff --git a/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yamlindex 3cc623faa..f23a96db8 100644--- a/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml@@ -26,6 +26,7 @@ spec:spec:{{- include "sie-cluster.imagePullSecrets" . | nindent 6 }}serviceAccountName: {{ include "sie-cluster.serviceAccountName" . }}+ automountServiceAccountToken: falsecontainers:- name: mcp-edgeimage: {{ include "sie-cluster.mcpEdge.image" . }}diff --git a/deploy/helm/sie-cluster/templates/nats-auth-secrets.yaml b/deploy/helm/sie-cluster/templates/nats-auth-secrets.yamlnew file mode 100644index 000000000..bef882fe8--- /dev/null+++ b/deploy/helm/sie-cluster/templates/nats-auth-secrets.yaml@@ -0,0 +1,34 @@+{{- include "sie-cluster.nats.validateAuth" . }}+{{- if and (include "sie-cluster.nats.authEnabled" .) .Values.nats.install }}+{{- $auth := .Values.nats.auth | default dict }}+{{- $components := include "sie-cluster.nats.authComponents" . | fromJsonArray }}+{{- if .Values.nats.config.cluster.enabled }}+{{- $components = append $components "route" }}+{{- end }}+{{- range $component := $components }}+{{- if not (dig "existingSecrets" $component "" $auth) }}+{{- $name := include "sie-cluster.nats.authSecretName" (dict "auth" $auth "release" $.Release.Name "component" $component) }}+{{- $password := printf "%s%s" (randAlpha 1) (randAlphaNum 47) | b64enc }}+{{- with lookup "v1" "Secret" (include "sie-cluster.namespace" $) $name }}+{{- $existing := index (.data | default dict) "password" | default "" }}+{{- include "sie-cluster.nats.validateReusedPassword" (dict "name" $name "data" $existing) }}+{{- $password = $existing }}+{{- end }}+---+apiVersion: v1+kind: Secret+metadata:+ name: {{ $name }}+ namespace: {{ include "sie-cluster.namespace" $ }}+ labels:+ {{- include "sie-cluster.labels" $ | nindent 4 }}+ app.kubernetes.io/component: nats-auth+ sie.superlinked.com/nats-user: {{ include "sie-cluster.nats.authUser" $component }}+ annotations:+ helm.sh/resource-policy: keep+type: Opaque+data:+ password: {{ $password | quote }}+{{- end }}+{{- end }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/rbac.yaml b/deploy/helm/sie-cluster/templates/rbac.yamlindex ffcc7cc44..bab823d0a 100644--- a/deploy/helm/sie-cluster/templates/rbac.yaml+++ b/deploy/helm/sie-cluster/templates/rbac.yaml@@ -33,6 +33,9 @@ subjects:# Role for gateway to manage resource pools (ConfigMaps + Leases)# Pools use ConfigMap for spec/status and Lease for TTL# See: Rust gateway pool management+# Pool ConfigMap names are dynamic, so the rule cannot use resourceNames and+# covers every ConfigMap in the namespace, including the NATS server+# configuration. Only gateway pods mount a token for this ServiceAccount.apiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata:diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex 53c64fb37..a5c8845bd 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -40,7 +40,7 @@ fast at render time.the gateway-deployment render guards exist to prevent. The sidecar'ssie-config credential comes only from config.auth, so SIE_ADMIN_TOKEN andSIE_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") -}}+{{- $reservedSidecarEnv := concat $reservedOtelEnv (list "SIE_ADMIN_TOKEN" "SIE_BUNDLE" "SIE_CONFIG_SERVICE_TOKEN" "SIE_GPU_COUNT" "SIE_HEALTH_PUBLISH_ENABLED" "SIE_HEALTH_PUBLISH_INTERVAL_MS" "SIE_MACHINE_PROFILE" "SIE_NATS_PASSWORD" "SIE_NATS_USER" "SIE_OTEL_LANE" "SIE_POOL" "SIE_STREAM_MAX_AGE_S" "SIE_STREAM_REPLICAS" "SIE_STREAM_STORAGE" "SIE_WORKER_ID") -}}{{- 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 }}@@ -239,6 +239,7 @@ spec:runtimeClassName: {{ $root.Values.workers.common.runtimeClassName | quote }}{{- end }}serviceAccountName: {{ include "sie-cluster.serviceAccountName" $root }}+ automountServiceAccountToken: falseterminationGracePeriodSeconds: 65securityContext:# SIE server runs as sie user (uid 1000, gid 1000)@@ -535,6 +536,7 @@ spec:{{- if $root.Values.nats.enabled }}- name: SIE_NATS_URLvalue: {{ $root.Values.nats.url | default (printf "nats://%s:4222" ($root.Values.nats.serviceName | default (printf "%s-nats" $root.Release.Name))) | quote }}+ {{- include "sie-cluster.nats.clientAuthEnv" (dict "root" $root "component" "worker") | nindent 12 }}{{- end }}{{- if $root.Values.config.enabled }}- name: SIE_NATS_CONFIG_TRUSTED_PRODUCERSdiff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 6935ebcfd..01ac8fc5b 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -1447,12 +1447,47 @@ nats:# -- Override the NATS service name used to build the default SIE_NATS_URL.# Defaults to "<release>-nats" if not set.serviceName: ""+ # -- NATS authentication. sie-config, the gateway, and the worker sidecars+ # each connect as their own user (sie-config, sie-gateway, sie-worker), and+ # the bundled server limits each user to the subjects it needs and refuses+ # anonymous connections. See "NATS authentication" in the chart README for+ # the permission matrix, password rotation, and the upgrade path.+ auth:+ # -- Authenticate every NATS connection. Set to false only to run without+ # authentication (for example an external server without it).+ enabled: true+ # -- Also accept anonymous connections, with unrestricted permissions,+ # on the bundled server. A temporary aid for upgrading an existing+ # release: pods that predate authentication keep working until they are+ # replaced. Once every pod has restarted, upgrade again with+ # `--set nats.auth.allowAnonymous=false`; `--reuse-values` and+ # `--reset-then-reuse-values` keep it on.+ allowAnonymous: false+ # -- Existing Secrets, each holding the component's NATS password under+ # the key `password`. For the bundled server it must be letters and digits+ # and start with a letter, because the server parses it as a+ # configuration value. An empty name makes the chart generate+ # "<release>-nats-auth-<component>". Required for config, gateway, and+ # worker when nats.install=false.+ existingSecrets:+ config: ""+ gateway: ""+ worker: ""+ # Password of the cluster route user, used when+ # nats.config.cluster.enabled=true on the bundled server.+ route: ""# -- JetStream configuration for the work queue.# JetStream is required for inference (the gateway is queue-only).# It is NOT required for config distribution (plain NATS pub/sub).# NOTE: These keys are passed to the NATS sub-chart (nats/nats) which expects# config.jetstream.memoryStore.maxSize (not memStorage/size).config:+ # Chart-owned: renders the NATS users and permissions from nats.auth.+ # Keep the sieNatsAuth keys here, under cluster.merge, and under+ # container.env when adding other settings next to them.+ merge:+ sieNatsAuth:+ $tplYamlSpread: '{{ include "sie-cluster.nats.server.configMerge" . }}'# -- NATS server clustering. Off by default: a single NATS pod is the# shipped topology. A replicated work queue# (queueRouting.streamReplicas > 1) needs this enabled with@@ -1460,6 +1495,9 @@ nats:cluster:enabled: falsereplicas: 3+ merge:+ sieNatsAuth:+ $tplYamlSpread: '{{ include "sie-cluster.nats.server.clusterMerge" . }}'jetstream:# -- Enable JetStream for the NATS work queue.# Required when clusterRouting=queue (the default).@@ -1485,6 +1523,14 @@ nats:pvc:enabled: truesize: 10Gi+ container:+ env:+ sieNatsAuth:+ $tplYamlSpread: '{{ include "sie-cluster.nats.server.env" . }}'+ # -- The nats-box debugging pod and its `helm test` pod connect without+ # credentials, which the authenticated server refuses.+ natsBox:+ enabled: false# -- Prometheus NATS exporter sidecar.# Exposes NATS server internals (connections, JetStream streams/consumers) to Prometheus.promExporter:diff --git a/packages/sie_config/src/sie_config/nats_publisher.py b/packages/sie_config/src/sie_config/nats_publisher.pyindex fa2543a70..25c7fa479 100644--- a/packages/sie_config/src/sie_config/nats_publisher.py+++ b/packages/sie_config/src/sie_config/nats_publisher.py@@ -41,6 +41,44 @@ class PartialPublishError(RuntimeError):)+def _replace_userinfo(url: str, replacement: str | None) -> str:+ """Return ``url`` with each server's ``user[:password]@`` userinfo replaced.++ The userinfo becomes ``replacement@``, or is removed when ``replacement`` is ``None``.+ """+ servers = []+ for server in url.split(","):+ scheme, sep, rest = server.partition("://")+ if not sep:+ scheme, rest = "", server+ authority_end = min((i for i in (rest.find("/"), rest.find("?"), rest.find("#")) if i >= 0), default=len(rest))+ at = rest.rfind("@", 0, authority_end)+ if at >= 0:+ rest = rest[at + 1 :] if replacement is None else replacement + rest[at:]+ servers.append(f"{scheme}{sep}{rest}")+ return ",".join(servers)+++def _redact_userinfo(url: str) -> str:+ """Return ``url`` with any ``user[:password]@`` userinfo replaced, for logs."""+ return _replace_userinfo(url, "<redacted>")+++def _credentials_from_env() -> tuple[str, str] | None:+ """NATS user and password from ``SIE_NATS_USER`` / ``SIE_NATS_PASSWORD``.++ Returns ``None`` when neither is set and raises ``ValueError`` when only one is.+ """+ user = os.environ.get("SIE_NATS_USER", "")+ password = os.environ.get("SIE_NATS_PASSWORD", "")+ if not user and not password:+ return None+ if not user or not password:+ msg = "SIE_NATS_USER and SIE_NATS_PASSWORD must be set together"+ raise ValueError(msg)+ return user, password++def _get_router_id() -> str:"""Get unique publisher identifier from hostname or env.@@ -65,11 +103,16 @@ class NatsPublisher:Gracefully degrades when NATS is unavailable -- config mutations are blocked.Args:- nats_url: NATS connection URL. Default: nats://localhost:4222+ nats_url: NATS connection URL. Default: nats://localhost:4222.+ Credentials come from ``SIE_NATS_USER`` / ``SIE_NATS_PASSWORD``;+ userinfo in the URL is removed before connecting."""def __init__(self, nats_url: str | None = None) -> None:self._nats_url = nats_url or os.environ.get("SIE_NATS_URL", "nats://localhost:4222")+ self._connect_url = _replace_userinfo(self._nats_url, None)+ self._log_url = _redact_userinfo(self._nats_url)+ self._credentials = _credentials_from_env()self._nc: nats.NATS | None = Noneself._router_id = _get_router_id()self._connected = False@@ -87,6 +130,19 @@ class NatsPublisher:returnself._boot_connect_task = asyncio.create_task(self.connect())+ async def _connect_client(self) -> nats.NATS:+ user, password = self._credentials or (None, None)+ return await nats.connect(+ self._connect_url,+ reconnected_cb=self._handle_reconnect,+ disconnected_cb=self._handle_disconnect,+ error_cb=self._handle_error,+ max_reconnect_attempts=-1,+ reconnect_time_wait=2,+ user=user,+ password=password,+ )+@propertydef connected(self) -> bool:"""Whether NATS connection is active."""@@ -122,19 +178,12 @@ class NatsPublisher:)try:self._nc = await asyncio.wait_for(- nats.connect(- self._nats_url,- reconnected_cb=self._handle_reconnect,- disconnected_cb=self._handle_disconnect,- error_cb=self._handle_error,- max_reconnect_attempts=-1,- reconnect_time_wait=2,- ),+ self._connect_client(),timeout=budget,)self._connected = Truesie_metrics.set_nats_connected(True)- logger.info("Connected to NATS at %s (router_id=%s)", self._nats_url, self._router_id)+ logger.info("Connected to NATS at %s (router_id=%s)", self._log_url, self._router_id)returnexcept TimeoutError:self._nc = None@@ -142,7 +191,7 @@ class NatsPublisher:sie_metrics.set_nats_connected(False)logger.warning("NATS at %s not ready within %.0fs - retries continue in background",- self._nats_url,+ self._log_url,budget,)except Exception: # noqa: BLE001 -- graceful degradation when NATS unavailable@@ -151,7 +200,7 @@ class NatsPublisher:sie_metrics.set_nats_connected(False)logger.warning("Failed to connect to NATS at %s -- config mutations will be blocked until reconnect",- self._nats_url,+ self._log_url,exc_info=True,)@@ -175,19 +224,12 @@ class NatsPublisher:logger.debug("Failed to drain stale NATS client", exc_info=True)self._nc = None- self._nc = await nats.connect(- self._nats_url,- reconnected_cb=self._handle_reconnect,- disconnected_cb=self._handle_disconnect,- error_cb=self._handle_error,- max_reconnect_attempts=-1,- reconnect_time_wait=2,- )+ self._nc = await self._connect_client()self._connected = Truesie_metrics.set_nats_connected(True)logger.info("Connected to NATS at %s (router_id=%s) after startup deferral",- self._nats_url,+ self._log_url,self._router_id,)return@@ -370,7 +412,7 @@ class NatsPublisher:"""Handle NATS reconnection."""self._connected = Truesie_metrics.set_nats_connected(True)- logger.info("Reconnected to NATS at %s", self._nats_url)+ logger.info("Reconnected to NATS at %s", self._log_url)async def _handle_disconnect(self) -> None:"""Handle NATS disconnection."""diff --git a/packages/sie_config/tests/test_nats_publisher.py b/packages/sie_config/tests/test_nats_publisher.pyindex 889b1dd6b..dff645cd2 100644--- a/packages/sie_config/tests/test_nats_publisher.py+++ b/packages/sie_config/tests/test_nats_publisher.py@@ -4,7 +4,7 @@ import loggingfrom unittest.mock import AsyncMock, patchimport pytest-from sie_config.nats_publisher import _ALL_SUBJECT, NatsPublisher+from sie_config.nats_publisher import _ALL_SUBJECT, NatsPublisher, _redact_userinfo, _replace_userinfoclass TestNatsPublisherConnect:@@ -95,6 +95,98 @@ class TestNatsPublisherConnect:await publisher.disconnect()+class TestNatsPublisherCredentials:+ @pytest.mark.asyncio+ async def test_connect_sends_credentials_from_env(self, monkeypatch: pytest.MonkeyPatch) -> None:+ password = "nats-password-" + "value"+ monkeypatch.setenv("SIE_NATS_USER", "sie-config")+ monkeypatch.setenv("SIE_NATS_PASSWORD", password)+ publisher = NatsPublisher(nats_url="nats://nats:4222")+ client = AsyncMock()+ client.is_connected = True+ with patch("nats.connect", AsyncMock(return_value=client)) as connect:+ await publisher.connect()+ assert connect.call_args.args == ("nats://nats:4222",)+ assert connect.call_args.kwargs["user"] == "sie-config"+ assert connect.call_args.kwargs["password"] == password+ assert publisher.connected+ await publisher.disconnect()++ @pytest.mark.asyncio+ async def test_connect_without_credentials(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("SIE_NATS_USER", raising=False)+ monkeypatch.delenv("SIE_NATS_PASSWORD", raising=False)+ publisher = NatsPublisher(nats_url="nats://nats:4222")+ client = AsyncMock()+ client.is_connected = True+ with patch("nats.connect", AsyncMock(return_value=client)) as connect:+ await publisher.connect()+ assert connect.call_args.kwargs["user"] is None+ assert connect.call_args.kwargs["password"] is None+ await publisher.disconnect()++ @pytest.mark.parametrize("set_var", ["SIE_NATS_USER", "SIE_NATS_PASSWORD"])+ def test_user_and_password_must_be_set_together(self, monkeypatch: pytest.MonkeyPatch, set_var: str) -> None:+ monkeypatch.delenv("SIE_NATS_USER", raising=False)+ monkeypatch.delenv("SIE_NATS_PASSWORD", raising=False)+ monkeypatch.setenv(set_var, "value")+ with pytest.raises(ValueError, match="must be set together"):+ NatsPublisher(nats_url="nats://nats:4222")++ @pytest.mark.asyncio+ async def test_logs_do_not_contain_url_credentials(self, caplog: pytest.LogCaptureFixture) -> None:+ publisher = NatsPublisher(nats_url="nats://url-user:url-secret@nats:4222")+ client = AsyncMock()+ client.is_connected = True+ with caplog.at_level(logging.DEBUG):+ with patch("nats.connect", side_effect=ConnectionRefusedError("refused")):+ await publisher.connect()+ await publisher.disconnect()+ with patch("nats.connect", AsyncMock(return_value=client)):+ await publisher.connect()+ await publisher._handle_reconnect()+ await publisher.disconnect()+ assert "nats://<redacted>@nats:4222" in caplog.text+ assert "url-secret" not in caplog.text+ assert "url-user" not in caplog.text++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ ("nats://nats:4222", "nats://nats:4222"),+ ("nats://user:secret@nats:4222", "nats://<redacted>@nats:4222"),+ ("tls://token@a:4222,nats://b:4222/x@y", "tls://<redacted>@a:4222,nats://b:4222/x@y"),+ ("user:p@ss@host", "<redacted>@host"),+ ],+ )+ def test_redact_userinfo(self, url: str, expected: str) -> None:+ assert _redact_userinfo(url) == expected++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ ("nats://nats:4222", "nats://nats:4222"),+ ("nats://user:secret@nats:4222", "nats://nats:4222"),+ ("tls://token@a:4222,nats://b:4222/x@y", "tls://a:4222,nats://b:4222/x@y"),+ ("user:p@ss@host", "host"),+ ],+ )+ def test_remove_userinfo(self, url: str, expected: str) -> None:+ assert _replace_userinfo(url, None) == expected++ @pytest.mark.asyncio+ async def test_connect_does_not_pass_url_credentials(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("SIE_NATS_USER", raising=False)+ monkeypatch.delenv("SIE_NATS_PASSWORD", raising=False)+ publisher = NatsPublisher(nats_url="nats://url-user:url-secret@nats:4222")+ client = AsyncMock()+ client.is_connected = True+ with patch("nats.connect", AsyncMock(return_value=client)) as connect:+ await publisher.connect()+ assert connect.call_args.args == ("nats://nats:4222",)+ await publisher.disconnect()++class TestNatsPublisherPublish:@pytest.mark.asyncioasync def test_publish_raises_when_not_connected(self) -> None:diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex 150e2c753..3eea4ad77 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -89,7 +89,9 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| `SIE_GATEWAY_K8S_SERVICE` | `sie-worker` | K8s service name || `SIE_GATEWAY_K8S_PORT` | `8080` | K8s worker port || `SIE_GATEWAY_HEALTH_MODE` | `ws` | Health mode: `ws` or `nats` |-| `SIE_NATS_URL` | | NATS server URL. The process can start without it, but inference requests will return `503` until a usable client exists |+| `SIE_NATS_URL` | | NATS server URL. The process can start without it, but inference requests will return `503` until a usable client exists. Credentials in the URL are not used; logs show the URL with any userinfo redacted |+| `SIE_NATS_USER` | | NATS user (Helm sets `sie-gateway`). Set together with `SIE_NATS_PASSWORD`; setting only one fails startup |+| `SIE_NATS_PASSWORD` | | NATS password of `SIE_NATS_USER`. Redacted in `Config` debug output || `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) |diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 4b7cf5645..5a213659e 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -205,7 +205,8 @@ Operational consequence: adding or changing a bundle in `sie-config` propagatesIndependently of bootstrap and polling, `NatsManager` subscribes to `sie.config.models._all` (Core pub/sub) as soon as the NATS client is ready. For each incoming `ConfigNotification`:-- **Producer-trust check first.** The `producer_id` (wire key `router_id`) must be in the trusted-producer allowlist. Default allowlist is `["sie-config"]`, configurable via `SIE_NATS_CONFIG_TRUSTED_PRODUCERS=a,b,c`; Helm sets it to the rendered config Deployment name (for example `sie-sie-cluster-config`) so Kubernetes pod names from that Deployment match. Matching is exact equality OR K8s pod-name prefix (`sie-config` also matches `sie-config-5f7b6d8c-kxwvr` and `sie-config-0`, but not `sie-configuration`). Untrusted notifications are dropped before any registry mutation or epoch advance; a log warning names the rejected producer. Set `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER=true` to disable validation (dev/local only — `main.rs` emits a startup warning when this is on).+- **Transport check first.** A notification with a reply subject or any `Nats-` header is dropped and counted as `rejected_untrusted`. `sie-config` publishes plain core messages, while a NATS user that can manage JetStream streams or consumers can make the server itself deliver stored bytes to any subject past its publish permissions (stream republish and direct-get replies carry `Nats-Stream`/`Nats-Sequence` headers, consumer deliveries carry a `$JS.ACK` reply subject). With the Helm chart's NATS users, only `sie-config` may publish on `sie.config.models.>`, so this check closes the remaining server-side path.+- **Producer-trust check next.** The `producer_id` (wire key `router_id`) must be in the trusted-producer allowlist. Default allowlist is `["sie-config"]`, configurable via `SIE_NATS_CONFIG_TRUSTED_PRODUCERS=a,b,c`; Helm sets it to the rendered config Deployment name (for example `sie-sie-cluster-config`) so Kubernetes pod names from that Deployment match. Matching is exact equality OR K8s pod-name prefix (`sie-config` also matches `sie-config-5f7b6d8c-kxwvr` and `sie-config-0`, but not `sie-configuration`). Untrusted notifications are dropped before any registry mutation or epoch advance; a log warning names the rejected producer. Set `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER=true` to disable validation (dev/local only — `main.rs` emits a startup warning when this is on).- An **empty-or-whitespace `model_config` body** (pure epoch bump) advances `ConfigEpoch` via `set_max(notification.epoch)` and returns.- A non-empty body is parsed as `ModelConfig` YAML. If the parse fails, the epoch is NOT advanced and the event is logged. The poller will catch up.- On successful parse, `ModelRegistry.add_model_config` is called. If it returns `Ok`, the epoch is advanced. If it returns `Err` (e.g. append-only conflict, unroutable adapter), the epoch is NOT advanced.@@ -313,7 +314,7 @@ Per-subject transport:| Inference results | `_INBOX.{router_id}.{request_id}` | NATS Core | Gateway is waiting synchronously; a brief blip after publish but before delivery means the result is lost and the client may retry (the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5` — see §2). Result payload is msgpack. || Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (section 4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through backend IPC. || Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply, plus `unsupported_models` when that hash covers models the worker cannot serve. `packages/wire-fixtures/worker_status.json` pins the heartbeat field set for the sidecar and the gateway. Helm sidecar deployments set `health_mode=nats`; the gateway binary default remains `ws` so standalone/test deployments can use the Python WebSocket path. |-| DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; gateway replicas subscribe in `queue/dlq.rs` and publish to `DEAD_LETTERS` with a deterministic `Nats-Msg-Id`, so JetStream dedupes replica fan-out. |+| DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; gateway replicas subscribe in `queue/dlq.rs` and publish to `DEAD_LETTERS` with a deterministic `Nats-Msg-Id`, so JetStream dedupes replica fan-out. Genuine advisories carry no reply subject and no headers; the listener drops any that do, because a stream republish can deliver forged advisories on this subject. || DLQ storage | `sie.dlq.{model_token}` | JetStream | Single stream `DEAD_LETTERS` (Limits retention, 24 h `max_age`) captures `sie.dlq.>`. Storage and replicas track the work-queue setting (`SIE_STREAM_STORAGE` / `SIE_STREAM_REPLICAS`, memory/1 by default), so a memory-backed DLQ is erased by the same broker restart that erases the work it recorded. `model_token` is derived from the advisory's original work subject by taking the model segment and replacing `/` with `_`. |### 8.2 Work-stream configuration and the model-ID constraint@@ -459,7 +460,8 @@ The gateway has no persistent config store. `SIE_CONFIG_STORE_DIR` and `SIE_CONF- `sie-gateway` scales horizontally. Each replica maintains its own in-memory `ModelRegistry` and its own `ConfigEpoch`. They all converge on the same state via a combination of bootstrap, deltas, and the poller; they do not coordinate with each other.- Bundles live on `sie-config`'s filesystem at `SIE_BUNDLES_DIR` (default `/app/bundles`, set via `sharedPaths.bundlesDir`) and are baked into its image. `sie-config` reads them at startup, validates writes against them, and re-serves them over HTTP at `GET /v1/configs/bundles{,/{id}}`. The gateway fetches that surface during `state::config_bootstrap::bootstrap` and installs it via `ModelRegistry::install_bundles` — there is no second copy. The `gateway.embeddedConfigs` / `gateway.configMap` overlays still exist for the rare case of running the gateway without `sie-config` (e.g., self-contained smoke tests); they mount a ConfigMap at `/configs/bundles` which the registry's filesystem reload picks up before the (no-op) bootstrap runs. In all cases, updating bundles is a `sie-config` redeploy and the gateway picks up the change on its next bootstrap or poller-driven reconcile, not via a runtime API call.- Pools are stored in Kubernetes `ConfigMap`s and `Lease`s read/written by the gateway. `sie-config` is not involved in pool management.-- NATS / JetStream runs as its own workload. The gateway's `NatsManager` builds `async_nats::ConnectOptions` with `retry_on_initial_connect()` so the process does not fail to start if NATS is briefly unavailable; reconnect behavior after initial connect relies on `async-nats`'s default policy (indefinite reconnect with backoff).+- NATS / JetStream runs as its own workload. The gateway's `NatsManager` builds `async_nats::ConnectOptions` with `retry_on_initial_connect()` so the process does not fail to start if NATS is briefly unavailable; reconnect behavior after initial connect relies on `async-nats`'s default policy (indefinite reconnect with backoff). With `SIE_NATS_USER` / `SIE_NATS_PASSWORD` set it authenticates with `user_and_password`; an authentication failure surfaces as a NATS server-error event in the log while the client keeps retrying.+- NATS authentication: the Helm chart gives `sie-config`, the gateway, and the worker sidecars separate NATS users and limits each to the subjects in §8 (permission matrix in the chart README, "NATS authentication"). The gateway user publishes work, DLQ entries, and cancels, manages the `WORK_POOL_*` and `DEAD_LETTERS` streams (`$JS.API.STREAM.INFO.*`, `$JS.API.STREAM.CREATE.*`, `$JS.API.STREAM.UPDATE.*`), reads consumer info for backlog metrics, and subscribes to `sie.config.models._all`, `sie.health.>`, `_INBOX.>`, and the max-deliveries advisory. It cannot publish config deltas or delete streams. Worker sidecars use the inbox prefix `_INBOX_WORKER`, so the worker user can publish results into `_INBOX.{router_id}.{request_id}` without subscribing to the gateway's inboxes. The worker user keeps JetStream stream and consumer management, and the server does not check stream subjects against subscribe permissions, so worker credentials can still capture gateway inboxes into a stream; the chart README lists what the worker user can still do. Only gateway pods mount a Kubernetes API token.## 11. Known Operational Caveats@@ -516,14 +518,16 @@ Gateway (`sie-gateway`):- `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.- `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` — comma-separated producer allowlist for `sie.config.models._all`. Binary default is `sie-config`; Helm sets the release-scoped config Deployment name. Matching is exact OR K8s pod-name prefix (see §4.3). Untrusted notifications are dropped; the `config_poller` still closes the gap.- `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` — `true` disables producer validation entirely. Intended for local/dev. `main.rs` emits a startup warning when on.-- NATS connection variables per the existing gateway configuration.+- `SIE_NATS_URL` — NATS broker URL. Credentials in the URL are not used and are redacted in logs and `Config` debug output.+- `SIE_NATS_USER` / `SIE_NATS_PASSWORD` — NATS credentials. Both or neither; one alone fails startup. The password is redacted in `Config` debug output.Config service (`sie-config`):- `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_NATS_URL` — NATS broker URL. Publisher degrades gracefully if unreachable; mutations are blocked with `503` while the publisher is configured but disconnected. Logs show the URL with any userinfo redacted.+- `SIE_NATS_USER` / `SIE_NATS_PASSWORD` — NATS credentials (Helm sets user `sie-config`, the only user allowed to publish on `sie.config.models.>`). Both or neither; one alone fails startup.- `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.- `SIE_LOG_LEVEL`, `SIE_LOG_JSON` — log verbosity and structured-JSON toggle (both also exposed as CLI flags).diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex 568d3b8ed..b735a03f7 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -111,6 +111,10 @@ pub struct Config {// NATSpub nats_url: String,+ /// NATS user and password (`SIE_NATS_USER` / `SIE_NATS_PASSWORD`). Both+ /// empty connects without credentials; see `nats_credentials`.+ pub nats_user: String,+ pub nats_password: String,/// Trusted-producer allowlist for `sie.config.models._all`. Defaults/// to `["sie-config"]`. Incoming `ConfigNotification`s whose/// `producer_id` is not in this list are dropped (neither the epoch@@ -236,6 +240,45 @@ pub struct Config {pub public_base_url: Option<String>,}+/// NATS user/password pair presented on connect.+#[derive(Clone, PartialEq, Eq)]+pub struct NatsCredentials {+ pub user: String,+ pub password: String,+}++impl std::fmt::Debug for NatsCredentials {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("NatsCredentials")+ .field("user", &self.user)+ .field("password", &redacted_secret(&self.password))+ .finish()+ }+}++/// `url` with any `user[:password]@` userinfo replaced by `<redacted>@`, for+/// logs. NATS credentials belong in `SIE_NATS_USER` / `SIE_NATS_PASSWORD`;+/// the client ignores userinfo in `SIE_NATS_URL`.+pub fn redact_url_userinfo(url: &str) -> String {+ url.split(',')+ .map(|server| {+ let authority_start = server.find("://").map_or(0, |i| i + 3);+ let authority_end = server[authority_start..]+ .find(['/', '?', '#'])+ .map_or(server.len(), |i| authority_start + i);+ match server[authority_start..authority_end].rfind('@') {+ Some(at) => format!(+ "{}<redacted>{}",+ &server[..authority_start],+ &server[authority_start + at..]+ ),+ None => server.to_string(),+ }+ })+ .collect::<Vec<_>>()+ .join(",")+}+/// Render a secret string for `Debug` output: an empty value stays empty (so/// "unset" is still visible), any real value collapses to `<redacted>` so the/// credential never reaches logs.@@ -254,7 +297,8 @@ impl std::fmt::Debug for Config {/// preserving present/absent (and count) so misconfig is still diagnosable./// `config_modal_proxy_token` relies on `ModalProxyToken`'s own redacting/// `Debug`. `nats_url` / `payload_store_url` are connection URLs kept- /// visible on purpose (redacting them would hide the target host).+ /// visible on purpose (redacting them would hide the target host);+ /// `nats_url` drops any userinfo.fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.debug_struct("Config").field("host", &self.host)@@ -265,7 +309,10 @@ impl std::fmt::Debug for Config {.field("k8s_service", &self.k8s_service).field("k8s_port", &self.k8s_port).field("health_mode", &self.health_mode)- .field("nats_url", &self.nats_url)+ .field("nats_url", &redact_url_userinfo(&self.nats_url))+ .field("nats_user", &self.nats_user)+ // Secret: the NATS password (SIE_NATS_PASSWORD).+ .field("nats_password", &redacted_secret(&self.nats_password)).field("nats_config_trusted_producers",&self.nats_config_trusted_producers,@@ -762,6 +809,8 @@ impl Config {health_mode: env_default("SIE_GATEWAY_HEALTH_MODE", "ws"),nats_url: env::var("SIE_NATS_URL").unwrap_or_default(),+ nats_user: env::var("SIE_NATS_USER").unwrap_or_default(),+ nats_password: env::var("SIE_NATS_PASSWORD").unwrap_or_default(),nats_config_trusted_producers: {// Explicit opt-in to the legacy "trust anyone" behavior.if env_bool("SIE_NATS_CONFIG_TRUST_ANY_PRODUCER") {@@ -957,6 +1006,20 @@ impl Config {.find_map(|(level, message)| matches!(level, AuditLevel::Error).then_some(message))}+ /// Credentials for the NATS connection: `None` when neither+ /// `SIE_NATS_USER` nor `SIE_NATS_PASSWORD` is set, an error when only one+ /// of them is.+ pub fn nats_credentials(&self) -> Result<Option<NatsCredentials>, String> {+ match (self.nats_user.is_empty(), self.nats_password.is_empty()) {+ (true, true) => Ok(None),+ (false, false) => Ok(Some(NatsCredentials {+ user: self.nats_user.clone(),+ password: self.nats_password.clone(),+ })),+ _ => Err("SIE_NATS_USER and SIE_NATS_PASSWORD must be set together".to_string()),+ }+ }+/// Report NATS config-delta producer-trust soundness. Mirrors the/// pattern of `audit_auth` but scoped to the/// `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` /@@ -1941,7 +2004,9 @@ mod tests {("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"),+ ("SIE_NATS_URL", "nats://url-user:url-secret@nats-host:4222"),+ ("SIE_NATS_USER", "sie-gateway"),+ ("SIE_NATS_PASSWORD", "nats-password-secret"),],|| {let cfg = Config::load();@@ -1962,6 +2027,9 @@ mod tests {"tok-secret-2", // auth_tokens"wk-id-secret","ws-value-secret", // config_modal_proxy_token+ "nats-password-secret",+ "url-secret",+ "url-user",] {assert!(!dbg.contains(leaked),@@ -1977,10 +2045,66 @@ mod tests {dbg.contains("nats-host"),"non-secret nats_url must stay visible: {dbg}");+ assert!(+ dbg.contains("sie-gateway"),+ "non-secret nats_user must stay visible: {dbg}"+ );+ let credentials = cfg.nats_credentials().unwrap().unwrap();+ assert!(!format!("{credentials:?}").contains("nats-password-secret"));},);}+ #[test]+ fn nats_credentials_require_user_and_password_together() {+ without_env(&["SIE_NATS_USER", "SIE_NATS_PASSWORD"], || {+ assert_eq!(Config::load().nats_credentials(), Ok(None));+ });+ with_env(+ &[+ ("SIE_NATS_USER", "sie-gateway"),+ ("SIE_NATS_PASSWORD", "pw"),+ ],+ || {+ assert_eq!(+ Config::load().nats_credentials(),+ Ok(Some(NatsCredentials {+ user: "sie-gateway".to_string(),+ password: "pw".to_string(),+ }))+ );+ },+ );+ for (case, user, password) in [+ ("user only", "sie-gateway", ""),+ ("password only", "", "pw"),+ ] {+ with_env(+ &[("SIE_NATS_USER", user), ("SIE_NATS_PASSWORD", password)],+ || {+ assert!(Config::load().nats_credentials().is_err(), "{case}");+ },+ );+ }+ }++ #[test]+ fn redact_url_userinfo_hides_credentials_only() {+ assert_eq!(+ redact_url_userinfo("nats://nats-host:4222"),+ "nats://nats-host:4222"+ );+ assert_eq!(+ redact_url_userinfo("nats://user:secret@nats-host:4222"),+ "nats://<redacted>@nats-host:4222"+ );+ assert_eq!(+ redact_url_userinfo("tls://token@a:4222,nats://b:4222/x@y"),+ "tls://<redacted>@a:4222,nats://b:4222/x@y"+ );+ assert_eq!(redact_url_userinfo("user:p@ss@host"), "<redacted>@host");+ }+// ── audit_auth ─────────────────────────────────────────────────fn cfg_with_auth(@@ -1999,6 +2123,8 @@ mod tests {k8s_port: 0,health_mode: String::new(),nats_url: String::new(),+ nats_user: String::new(),+ nats_password: String::new(),nats_config_trusted_producers: Vec::new(),auth_mode: mode.to_string(),auth_tokens: tokens.into_iter().map(String::from).collect(),diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 60a948f0a..b192c4136 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -476,6 +476,8 @@ mod tests {k8s_port: 8080,health_mode: "ws".to_string(),nats_url: String::new(),+ nats_user: String::new(),+ nats_password: String::new(),nats_config_trusted_producers: vec!["sie-config".to_string()],auth_mode: "none".to_string(),auth_tokens: Vec::new(),diff --git a/packages/sie_gateway/src/handlers/health.rs b/packages/sie_gateway/src/handlers/health.rsindex b0a98f392..e58b31c60 100644--- a/packages/sie_gateway/src/handlers/health.rs+++ b/packages/sie_gateway/src/handlers/health.rs@@ -246,6 +246,8 @@ mod tests {k8s_port: 8080,health_mode: "ws".to_string(),nats_url: String::new(),+ nats_user: String::new(),+ nats_password: String::new(),nats_config_trusted_producers: vec!["sie-config".to_string()],auth_mode: "none".to_string(),auth_tokens: Vec::new(),diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex d255d42da..27ce16028 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -333,6 +333,8 @@ mod route_tests {k8s_port: 8080,health_mode: "ws".to_string(),nats_url: String::new(),+ nats_user: String::new(),+ nats_password: String::new(),nats_config_trusted_producers: vec!["sie-config".to_string()],auth_mode: "none".to_string(),auth_tokens: Vec::new(),diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex ebcdbf1aa..01457a651 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -14666,6 +14666,8 @@ mod tests {k8s_port: 0,health_mode: "http".to_string(),nats_url: String::new(),+ nats_user: String::new(),+ nats_password: String::new(),nats_config_trusted_producers: Vec::new(),auth_mode: "none".to_string(),auth_tokens: Vec::new(),diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex ad889d6b3..889d4c8d5 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -275,13 +275,16 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {// Config persistence lives in sie-config now; the gateway is pure// consumer. It gets its authoritative snapshot via the background// bootstrap task and then tracks live changes through NATS deltas.- let nats_manager = Arc::new(NatsManager::new_with_trusted_producers(- router_id.clone(),- config.nats_url.clone(),- Arc::clone(&model_registry),- config_epoch.clone(),- config.nats_config_trusted_producers.clone(),- ));+ let nats_manager = Arc::new(+ NatsManager::new_with_trusted_producers(+ router_id.clone(),+ config.nats_url.clone(),+ Arc::clone(&model_registry),+ config_epoch.clone(),+ config.nats_config_trusted_producers.clone(),+ )+ .with_credentials(config.nats_credentials()?),+ );if !config.nats_config_trusted_producers.is_empty() {tracing::info!(audit = "nats_config",diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex 0b4de6973..81b8f85be 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -462,6 +462,8 @@ mod tests {k8s_port: 0,health_mode: String::new(),nats_url: String::new(),+ nats_user: String::new(),+ nats_password: String::new(),nats_config_trusted_producers: Vec::new(),auth_mode: mode.to_string(),auth_tokens: tokens.into_iter().map(String::from).collect(),diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex a95ed7c32..50bf8f8df 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -21,6 +21,7 @@ use serde::{Deserialize, Serialize};use tokio::sync::RwLock;use tracing::{error, info, warn};+use crate::config::{redact_url_userinfo, NatsCredentials};use crate::observability::metrics::{self as telemetry, ConfigOperation, ConfigOutcome};use crate::state::config_epoch::ConfigEpoch;use crate::state::model_registry::ModelRegistry;@@ -36,6 +37,30 @@ fn notification_operation(notification: &ConfigNotification) -> ConfigOperation}}+/// Why `msg` did not come from a plain client publish, or `None` when it did.+///+/// sie-config publishes config notifications, and the server emits JetStream+/// advisories, with neither a reply subject nor headers. A NATS user that may+/// manage JetStream streams or consumers can make the server itself deliver+/// stored bytes to any subject, past that user's publish permissions: stream+/// republish and direct-get replies carry `Nats-Stream`/`Nats-Sequence`+/// headers, and consumer deliveries carry a `$JS.ACK` reply subject. Dropping+/// those keeps these subjects limited to the NATS users allowed to publish on+/// them.+pub(crate) fn server_originated(msg: &async_nats::Message) -> Option<&'static str> {+ if msg.reply.is_some() {+ return Some("reply subject set");+ }+ let has_server_header = msg.headers.as_ref().is_some_and(|headers| {+ headers.iter().any(|(name, _)| {+ let name: &str = name.as_ref();+ name.get(..5)+ .is_some_and(|prefix| prefix.eq_ignore_ascii_case("nats-"))+ })+ });+ has_server_header.then_some("JetStream header present")+}+/// Default trusted-producer allowlist for `sie.config.models._all`. Only/// `sie-config` is expected to publish on these subjects; every other/// `producer_id` is dropped in `apply_notification`. Matched as exact@@ -85,6 +110,7 @@ pub struct NatsManager {/// Allowlist of `producer_id` values whose notifications are applied./// An empty `Vec` disables validation (trust any producer).trusted_producers: Vec<String>,+ credentials: Option<NatsCredentials>,}impl NatsManager {@@ -128,9 +154,16 @@ impl NatsManager {config_epoch,reconnect_notify: Arc::new(tokio::sync::Notify::new()),trusted_producers,+ credentials: None,}}+ /// Authenticate the connection with these credentials.+ pub fn with_credentials(mut self, credentials: Option<NatsCredentials>) -> Self {+ self.credentials = credentials;+ self+ }+/// Test-only: current trusted-producer allowlist.#[cfg(test)]pub fn trusted_producers(&self) -> &[String] {@@ -158,7 +191,12 @@ impl NatsManager {let reconnect_notify_clone = Arc::clone(&self.reconnect_notify);- let client = async_nats::ConnectOptions::new()+ let mut options = async_nats::ConnectOptions::new();+ if let Some(credentials) = &self.credentials {+ options =+ options.user_and_password(credentials.user.clone(), credentials.password.clone());+ }+ let client = options.retry_on_initial_connect().connection_timeout(Duration::from_secs(5)).reconnect_delay_callback(|_attempts| Duration::from_secs(2))@@ -193,7 +231,12 @@ impl NatsManager {.connect(&self.nats_url).await?;- info!(url = %self.nats_url, gateway_id = %self.gateway_id, "connected to NATS");+ info!(+ url = %redact_url_userinfo(&self.nats_url),+ user = self.credentials.as_ref().map_or("", |c| c.user.as_str()),+ gateway_id = %self.gateway_id,+ "connected to NATS"+ );telemetry::set_messaging_client_ready(true);*self.client.write().await = Some(client);@@ -230,6 +273,17 @@ impl NatsManager {async fn handle_subscription(&self, mut subscriber: async_nats::Subscriber) {while let Some(msg) = subscriber.next().await {+ if let Some(reason) = server_originated(&msg) {+ telemetry::record_config_operation(+ ConfigOperation::DeltaModel,+ ConfigOutcome::RejectedUntrusted,+ );+ warn!(+ reason,+ "dropping config notification that was not published directly by a client"+ );+ continue;+ }let notification: ConfigNotification = match serde_json::from_slice(&msg.payload) {Ok(n) => n,Err(e) => {@@ -373,6 +427,48 @@ mod tests {use std::collections::HashMap;use std::fs;+ fn config_message(+ reply: Option<&str>,+ headers: Option<async_nats::HeaderMap>,+ ) -> async_nats::Message {+ async_nats::Message {+ subject: SUBJECT_ALL.into(),+ reply: reply.map(Into::into),+ payload: bytes::Bytes::from_static(b"{}"),+ headers,+ status: None,+ description: None,+ length: 0,+ }+ }++ #[test]+ fn server_originated_accepts_only_plain_client_publishes() {+ assert_eq!(server_originated(&config_message(None, None)), None);++ let mut app_headers = async_nats::HeaderMap::new();+ app_headers.insert("traceparent", "00-abc-def-01");+ assert_eq!(+ server_originated(&config_message(None, Some(app_headers))),+ None+ );++ assert!(server_originated(&config_message(+ Some("$JS.ACK.WORK_x.pushc.1.1.1.1.0"),+ None+ ))+ .is_some());++ for name in ["Nats-Stream", "nats-sequence", "NATS-SUBJECT"] {+ let mut headers = async_nats::HeaderMap::new();+ headers.insert(name, "WORK_x");+ assert!(+ server_originated(&config_message(None, Some(headers))).is_some(),+ "{name}"+ );+ }+ }+#[test]fn test_config_notification_serde() {let notification = ConfigNotification {diff --git a/packages/sie_gateway/src/queue/dlq.rs b/packages/sie_gateway/src/queue/dlq.rsindex d3b0ad392..b88a6e304 100644--- a/packages/sie_gateway/src/queue/dlq.rs+++ b/packages/sie_gateway/src/queue/dlq.rs@@ -5,6 +5,7 @@ use futures_util::StreamExt;use tracing::{debug, error, info, warn};use super::stream_durability;+use crate::nats::manager::server_originated;use crate::observability::metrics::{self as telemetry, QueueEvent, QueueEventOutcome};const DLQ_STREAM_NAME: &str = "DEAD_LETTERS";@@ -123,6 +124,14 @@ impl DlqListener {) {while let Some(msg) = subscriber.next().await {let subject = msg.subject.as_str();+ if let Some(reason) = server_originated(&msg) {+ warn!(+ subject = %subject,+ reason,+ "dropping max-deliveries advisory that the server did not emit itself"+ );+ continue;+ }let payload = msg.payload.to_vec();// Parse the advisory to extract stream/consumer infodiff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex 504a4da4b..a276fedbb 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -959,6 +959,8 @@ mod flat_404_tests {k8s_port: 8080,health_mode: "ws".to_string(),nats_url: String::new(),+ nats_user: String::new(),+ nats_password: String::new(),nats_config_trusted_producers: vec!["sie-config".to_string()],// Auth disabled so requests reach the router and exercise the// route table itself — the flat 404 must come from thediff --git a/packages/sie_gateway/tests/nats_auth.rs b/packages/sie_gateway/tests/nats_auth.rsnew file mode 100644index 000000000..8ddf2050c--- /dev/null+++ b/packages/sie_gateway/tests/nats_auth.rs@@ -0,0 +1,433 @@+//! Integration test: the gateway on an authenticated NATS server.+//!+//! Runs `nats-server` with the configuration the Helm chart renders by+//! default (`tools/ci/fixtures/sie-cluster-nats.conf`, which+//! `tools/ci/tests/test_helm_render.py` keeps equal to the chart). Skips when+//! `nats-server` is not on `PATH`, unless `NATS_URL` is set as in CI, where a+//! missing binary fails the test.++use std::net::TcpStream;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::sync::Arc;+use std::time::Duration;++use async_nats::jetstream;+use futures_util::StreamExt;+use sie_gateway::config::NatsCredentials;+use sie_gateway::nats::manager::NatsManager;+use sie_gateway::queue::dlq::DlqListener;+use sie_gateway::queue::payload_store::DisabledPayloadStore;+use sie_gateway::queue::publisher::{WorkPublisher, WorkStreamConfig};+use sie_gateway::state::config_epoch::ConfigEpoch;+use sie_gateway::state::model_registry::ModelRegistry;++struct Passwords {+ config: String,+ gateway: String,+ worker: String,+}++fn random_password() -> String {+ format!("p{}", uuid::Uuid::new_v4().simple())+}++struct NatsServer {+ child: Child,+ url: String,+ passwords: Passwords,+ dir: tempfile::TempDir,+}++impl Drop for NatsServer {+ fn drop(&mut self) {+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++fn nats_server_binary() -> Option<PathBuf> {+ let paths = std::env::var_os("PATH")?;+ std::env::split_paths(&paths)+ .map(|dir| dir.join("nats-server"))+ .find(|path| path.is_file())+}++async fn start_nats() -> Option<NatsServer> {+ let Some(binary) = nats_server_binary() else {+ assert!(+ std::env::var_os("NATS_URL").is_none(),+ "nats-server must be on PATH when NATS_URL is set"+ );+ eprintln!("skipping: nats-server not on PATH");+ return None;+ };+ let config =+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/ci/fixtures/sie-cluster-nats.conf");+ let dir = tempfile::tempdir().expect("tempdir");+ let log = std::fs::File::create(dir.path().join("nats.log")).expect("log file");+ let passwords = Passwords {+ config: random_password(),+ gateway: random_password(),+ worker: random_password(),+ };+ let child = Command::new(binary)+ .arg("-c")+ .arg(&config)+ .args(["-a", "127.0.0.1", "-p", "-1", "-m", "-1"])+ .arg("--ports_file_dir")+ .arg(dir.path())+ .arg("-sd")+ .arg(dir.path().join("jetstream"))+ .arg("-P")+ .arg(dir.path().join("nats.pid"))+ .env("SERVER_NAME", "sie-gateway-auth-test")+ .env("SIE_NATS_AUTH_CONFIG_PASSWORD", &passwords.config)+ .env("SIE_NATS_AUTH_GATEWAY_PASSWORD", &passwords.gateway)+ .env("SIE_NATS_AUTH_WORKER_PASSWORD", &passwords.worker)+ .stdout(Stdio::null())+ .stderr(log)+ .spawn()+ .expect("start nats-server");+ let mut server = NatsServer {+ child,+ url: String::new(),+ passwords,+ dir,+ };+ for _ in 0..600 {+ if let Some(url) = listening_url(server.dir.path()) {+ server.url = url;+ return Some(server);+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ let log = std::fs::read_to_string(server.dir.path().join("nats.log")).unwrap_or_default();+ panic!("nats-server did not start:\n{log}");+}++/// The client URL from the `*.ports` file nats-server writes once it listens.+fn listening_url(dir: &Path) -> Option<String> {+ let ports = std::fs::read_dir(dir)+ .ok()?+ .filter_map(Result::ok)+ .find(|entry| entry.path().extension().is_some_and(|ext| ext == "ports"))?;+ let ports: serde_json::Value =+ serde_json::from_slice(&std::fs::read(ports.path()).ok()?).ok()?;+ let url = ports["nats"][0].as_str()?.to_string();+ let address = url.trim_start_matches("nats://").to_string();+ TcpStream::connect(address).ok().map(|_| url)+}++async fn connect_as(url: &str, user: &str, password: &str) -> async_nats::Client {+ async_nats::ConnectOptions::new()+ .user_and_password(user.to_string(), password.to_string())+ .connect(url)+ .await+ .unwrap_or_else(|e| panic!("connect as {user}: {e}"))+}++async fn connect_worker(nats: &NatsServer) -> async_nats::Client {+ async_nats::ConnectOptions::new()+ .user_and_password("sie-worker".to_string(), nats.passwords.worker.clone())+ .custom_inbox_prefix("_INBOX_WORKER")+ .connect(&nats.url)+ .await+ .expect("connect as sie-worker")+}++fn epoch_bump(epoch: u64) -> bytes::Bytes {+ serde_json::to_vec(&serde_json::json!({+ "router_id": "sie-config",+ "bundle_id": "default",+ "epoch": epoch,+ "bundle_config_hash": "",+ }))+ .expect("encode notification")+ .into()+}++async fn wait_for_epoch(epoch: &ConfigEpoch, want: u64) -> bool {+ for _ in 0..100 {+ if epoch.get() == want {+ return true;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ false+}++#[tokio::test]+async fn anonymous_and_wrong_password_connections_are_refused() {+ let Some(nats) = start_nats().await else {+ return;+ };+ assert!(async_nats::ConnectOptions::new()+ .connect(&nats.url)+ .await+ .is_err());+ assert!(async_nats::ConnectOptions::new()+ .user_and_password("sie-gateway".into(), nats.passwords.worker.clone())+ .connect(&nats.url)+ .await+ .is_err());+}++#[tokio::test]+async fn gateway_takes_config_deltas_only_from_the_sie_config_user() {+ let Some(nats) = start_nats().await else {+ return;+ };+ let dir = tempfile::tempdir().expect("tempdir");+ let epoch = ConfigEpoch::new();+ let manager = Arc::new(+ NatsManager::new_with_trusted_producers(+ "gateway-auth-test".to_string(),+ nats.url.clone(),+ Arc::new(ModelRegistry::new(dir.path(), dir.path(), false)),+ epoch.clone(),+ vec!["sie-config".to_string()],+ )+ .with_credentials(Some(NatsCredentials {+ user: "sie-gateway".to_string(),+ password: nats.passwords.gateway.clone(),+ })),+ );+ manager.connect().await.expect("gateway connect");+ let client = manager.get_client().await.expect("gateway client");+ for _ in 0..100 {+ if client.connection_state() == async_nats::connection::State::Connected {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ manager.start_subscription().await;+ client.flush().await.expect("gateway flush");++ let config = connect_as(&nats.url, "sie-config", &nats.passwords.config).await;+ config+ .publish("sie.config.models._all", epoch_bump(5))+ .await+ .expect("publish");+ config.flush().await.expect("config flush");+ assert!(+ wait_for_epoch(&epoch, 5).await,+ "the gateway applies a delta from sie-config"+ );++ let observer = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let mut seen = observer+ .subscribe("sie.config.models._all")+ .await+ .expect("subscribe");+ observer.flush().await.expect("observer flush");++ let worker = connect_worker(&nats).await;+ worker+ .publish("sie.config.models._all", epoch_bump(7))+ .await+ .expect("publish");+ worker.flush().await.expect("worker flush");++ jetstream::new(worker.clone())+ .create_stream(jetstream::stream::Config {+ name: "WORK_WORKER_republish".to_string(),+ subjects: vec!["sie.health.republish".to_string()],+ storage: jetstream::stream::StorageType::Memory,+ republish: Some(jetstream::stream::Republish {+ source: "sie.health.republish".to_string(),+ destination: "sie.config.models._all".to_string(),+ headers_only: false,+ }),+ ..Default::default()+ })+ .await+ .expect("the worker user may create streams");+ worker+ .publish("sie.health.republish", epoch_bump(9))+ .await+ .expect("publish");+ worker.flush().await.expect("worker flush");++ let delivered = tokio::time::timeout(Duration::from_secs(5), seen.next())+ .await+ .expect("the server republishes the stored bytes")+ .expect("subscription open");+ assert!(+ delivered+ .headers+ .as_ref()+ .is_some_and(|headers| headers.get("Nats-Stream").is_some()),+ "only the republished copy reaches the subject, with JetStream headers"+ );+ tokio::time::sleep(Duration::from_millis(500)).await;+ assert_eq!(+ epoch.get(),+ 5,+ "neither the refused publish nor the republished copy is applied"+ );+}++#[tokio::test]+async fn gateway_user_manages_work_streams_but_cannot_delete_them() {+ let Some(nats) = start_nats().await else {+ return;+ };+ let gateway = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let publisher = WorkPublisher::new(+ jetstream::new(gateway.clone()),+ "gateway-auth-test".to_string(),+ Arc::new(DisabledPayloadStore),+ Duration::from_secs(30),+ 1024,+ WorkStreamConfig {+ max_age: Duration::from_secs(300),+ storage: jetstream::stream::StorageType::Memory,+ num_replicas: 1,+ },+ );+ publisher+ .ensure_stream("authpool")+ .await+ .expect("the gateway user creates work streams");++ let context = jetstream::new(gateway);+ context+ .publish("sie.work.authpool.cpu.default.model", "work".into())+ .await+ .expect("publish work")+ .await+ .expect("work stored");+ assert!(context.delete_stream("WORK_POOL_authpool").await.is_err());+}++async fn dead_letters(context: &jetstream::Context) -> u64 {+ context+ .get_stream("DEAD_LETTERS")+ .await+ .expect("DEAD_LETTERS")+ .info()+ .await+ .expect("stream info")+ .state+ .messages+}++#[tokio::test]+async fn dlq_forwards_only_advisories_the_server_emits() {+ let Some(nats) = start_nats().await else {+ return;+ };+ let gateway = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let context = jetstream::new(gateway.clone());+ DlqListener::start(+ context.clone(),+ gateway.clone(),+ jetstream::stream::StorageType::Memory,+ 1,+ )+ .await+ .expect("DLQ listener");+ context+ .create_stream(jetstream::stream::Config {+ name: "WORK_POOL_dlq".into(),+ subjects: vec!["sie.work.dlq.*.*.*".into()],+ retention: jetstream::stream::RetentionPolicy::WorkQueue,+ storage: jetstream::stream::StorageType::Memory,+ ..Default::default()+ })+ .await+ .expect("pool stream");++ let worker = connect_worker(&nats).await;+ let worker_context = jetstream::new(worker.clone());+ worker_context+ .create_stream(jetstream::stream::Config {+ name: "FAKE_ADVISORY".into(),+ subjects: vec!["sie.health.fake-advisory".into()],+ storage: jetstream::stream::StorageType::Memory,+ republish: Some(jetstream::stream::Republish {+ source: "sie.health.fake-advisory".into(),+ destination: "$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.WORK_POOL_dlq.lane".into(),+ headers_only: false,+ }),+ ..Default::default()+ })+ .await+ .expect("the worker user may create streams");+ let forged = serde_json::json!({+ "type": "io.nats.jetstream.advisory.v1.max_deliver",+ "id": "forged",+ "stream": "WORK_POOL_dlq",+ "consumer": "lane",+ "stream_seq": 7,+ "deliveries": 3,+ "subject": "sie.work.dlq.l4.default.forged",+ });+ worker+ .publish(+ "sie.health.fake-advisory",+ serde_json::to_vec(&forged).expect("encode").into(),+ )+ .await+ .expect("publish");+ worker.flush().await.expect("worker flush");+ tokio::time::sleep(Duration::from_millis(500)).await;++ let consumer: jetstream::consumer::PullConsumer = worker_context+ .get_stream("WORK_POOL_dlq")+ .await+ .expect("pool stream")+ .create_consumer(jetstream::consumer::pull::Config {+ durable_name: Some("lane".into()),+ filter_subject: "sie.work.dlq.l4.default.*".into(),+ ack_wait: Duration::from_secs(1),+ max_deliver: 1,+ ..Default::default()+ })+ .await+ .expect("the worker user may create consumers");+ context+ .publish("sie.work.dlq.l4.default.model", "work".into())+ .await+ .expect("publish work")+ .await+ .expect("work stored");+ let mut first = consumer+ .fetch()+ .max_messages(1)+ .expires(Duration::from_secs(2))+ .messages()+ .await+ .expect("fetch");+ first+ .next()+ .await+ .expect("delivered")+ .expect("work message");+ tokio::time::sleep(Duration::from_millis(1500)).await;+ let mut again = consumer+ .fetch()+ .max_messages(1)+ .expires(Duration::from_millis(500))+ .messages()+ .await+ .expect("fetch");+ while again.next().await.is_some() {}++ let mut forwarded = 0;+ for _ in 0..50 {+ forwarded = dead_letters(&context).await;+ if forwarded > 0 {+ break;+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ tokio::time::sleep(Duration::from_millis(300)).await;+ assert_eq!(forwarded, 1, "the genuine advisory is forwarded");+ assert_eq!(+ dead_letters(&context).await,+ 1,+ "the republished advisory is not forwarded"+ );+}diff --git a/packages/sie_server_sidecar/README.md b/packages/sie_server_sidecar/README.mdindex 95b3442f6..d60531015 100644--- a/packages/sie_server_sidecar/README.md+++ b/packages/sie_server_sidecar/README.md@@ -38,6 +38,11 @@ authentication protocol. The listener restricts its socket node, validates adomain-separated request digest and route identity, caps frame/media/requestsizes, and rejects unresolved payload references.+NATS credentials come from `SIE_NATS_USER` and `SIE_NATS_PASSWORD`, which are+read from the environment only and must be set together. Credentials embedded+in `SIE_NATS_URL` are not used. The subjects the Helm chart's `sie-worker` user+may use are listed in the architecture guide.+With the `cloud-storage` feature, payload reads support S3, GCS, Azure Blob,and native `oss://` Alibaba OSS Signature V4. OSS requires `SIE_OSS_REGION` anduses explicit environment credentials or ACK RRSA OIDC only; node metadata,diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 0fbba0ac8..d07e290ff 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -183,6 +183,41 @@ tombstone filters that redelivery. Static inference already sent over backendIPC is not preempted; the gateway has removed its collector and drops the lateresult.+### Connection and permissions++The sidecar connects with the credentials in `SIE_NATS_USER` and+`SIE_NATS_PASSWORD`, which are read from the environment only (there are no+CLI flags for them, and `--help` hides the value of `SIE_NATS_URL`). Setting+only one of the two fails startup. Credentials in `SIE_NATS_URL` are not used,+and logs redact any userinfo in it. In the Helm chart only the sidecar+container of a worker pod receives the worker credentials, not the container+that runs model code.++The client uses the inbox prefix `_INBOX_WORKER` for its JetStream API replies+and pull deliveries. The chart's `sie-worker` user may subscribe to that+prefix, to `sie.config.models.*`, and to the three cancel subject trees, and+may publish results into the gateway's `_INBOX` subjects, heartbeats on+`sie.health.>`, acknowledgements on `$JS.ACK.>`, and the JetStream API calls+above: stream info, create, and update (the sidecar creates its+direct-dispatch stream and reconciles the pool stream), and consumer list,+info, create, delete, and pull. It cannot publish work, config deltas, or+cancels, subscribe to the gateway's inboxes, or delete or purge streams. Its+stream and consumer management still reaches other pools' streams, durables,+and the gateway's inboxes; the full matrix and what the worker user can still+do are in the chart README ("NATS authentication"). The worker pod mounts no+Kubernetes API token.++Because stream management lets the server deliver stored messages on a+worker's behalf past its publish permissions, the sidecar drops cancel+signals that carry a reply subject or a `Nats-` header, and drops (ACKs) work+that carries a `Nats-` header other than the gateway's `Nats-Msg-Id`. A+subject transform on the pool stream still adds work without such a header.++On the generation path the sidecar publishes a backend `publish` event only+when its reply subject equals the work item's `reply_subject`. The backend+runs model code, so it must not choose where the sidecar's NATS user+publishes.+Source: [`nats_consumer.rs`](../src/nats_consumer.rs),[`subject.rs`](../src/subject.rs), and the gateway[queue publisher](../../sie_gateway/src/queue/publisher.rs).@@ -464,8 +499,12 @@ The sidecar subscribes to bundle-scoped config deltas:sie.config.models.{bundle}```-Each notification is checked for trusted producer, bundle, epoch, and payload-size. Accepted deltas are forwarded to the colocated backend through+A notification with a reply subject or any `Nats-` header is dropped first:+`sie-config` publishes plain core messages, and such a delivery can only come+from the NATS server acting for a user that manages JetStream streams or+consumers (for example a stream's republish setting), past that user's publish+permissions. Each remaining notification is checked for trusted producer,+bundle, epoch, and payload size. Accepted deltas are forwarded to the colocated backend through`ApplyModelConfig`, together with the notification's `bundle_adapters` list forthis bundle when `sie-config` sends one. The backend returns the applied bundleconfig hash and `unsupported_models`, the routable ids that hash covers but thediff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 21608cfff..0623f69cc 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -5,6 +5,70 @@use std::path::PathBuf;+/// NATS user/password pair (`SIE_NATS_USER` / `SIE_NATS_PASSWORD`).+#[derive(Clone, PartialEq, Eq)]+pub struct NatsCredentials {+ pub user: String,+ pub password: String,+}++impl NatsCredentials {+ /// `None` when neither value is set, an error when only one is.+ pub fn from_parts(+ user: Option<String>,+ password: Option<String>,+ ) -> Result<Option<Self>, String> {+ let user = user.filter(|v| !v.is_empty());+ let password = password.filter(|v| !v.is_empty());+ match (user, password) {+ (None, None) => Ok(None),+ (Some(user), Some(password)) => Ok(Some(Self { user, password })),+ _ => Err("SIE_NATS_USER and SIE_NATS_PASSWORD must be set together".to_string()),+ }+ }++ /// Read `SIE_NATS_USER` / `SIE_NATS_PASSWORD`. They are environment-only+ /// (no CLI flags), so the password never appears in a process listing or+ /// in `--help`.+ pub fn from_env() -> Result<Option<Self>, String> {+ Self::from_parts(+ std::env::var("SIE_NATS_USER").ok(),+ std::env::var("SIE_NATS_PASSWORD").ok(),+ )+ }+}++impl std::fmt::Debug for NatsCredentials {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("NatsCredentials")+ .field("user", &self.user)+ .field("password", &"<redacted>")+ .finish()+ }+}++/// `url` with any `user[:password]@` userinfo replaced by `<redacted>@`, for+/// logs. The client ignores userinfo in `SIE_NATS_URL`.+pub fn redact_url_userinfo(url: &str) -> String {+ url.split(',')+ .map(|server| {+ let authority_start = server.find("://").map_or(0, |i| i + 3);+ let authority_end = server[authority_start..]+ .find(['/', '?', '#'])+ .map_or(server.len(), |i| authority_start + i);+ match server[authority_start..authority_end].rfind('@') {+ Some(at) => format!(+ "{}<redacted>{}",+ &server[..authority_start],+ &server[authority_start + at..]+ ),+ None => server.to_string(),+ }+ })+ .collect::<Vec<_>>()+ .join(",")+}+#[derive(Clone)]pub struct WorkerConfig {/// NATS server URL (e.g. `nats://localhost:4222`). Required for the@@ -13,6 +77,9 @@ pub struct WorkerConfig {/// touches NATS.pub nats_url: Option<String>,+ /// Credentials for the NATS connection; `None` connects without them.+ pub nats_credentials: Option<NatsCredentials>,+/// UDS path for the local-ingest listener (`SIE_SIDECAR_LOCAL_SOCKET`)./// Only read by `run_local()`; `None` on NATS deployments.pub local_socket_path: Option<PathBuf>,@@ -155,12 +222,14 @@ pub struct WorkerConfig {impl std::fmt::Debug for WorkerConfig {/// Hand-written so the bearer tokens (`gateway_api_key`,- /// `config_service_token`) print only as present or absent.+ /// `config_service_token`) print only as present or absent, and the NATS+ /// password and URL userinfo never print.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 WorkerConfig {nats_url,+ nats_credentials,local_socket_path,pool,bundle,@@ -191,7 +260,8 @@ impl std::fmt::Debug for WorkerConfig {health_publish_interval_ms,} = self;f.debug_struct("WorkerConfig")- .field("nats_url", nats_url)+ .field("nats_url", &nats_url.as_deref().map(redact_url_userinfo))+ .field("nats_credentials", nats_credentials).field("local_socket_path", local_socket_path).field("pool", pool).field("bundle", bundle)@@ -303,6 +373,7 @@ mod tests {fn sample() -> WorkerConfig {WorkerConfig {nats_url: Some("nats://localhost:4222".into()),+ nats_credentials: None,local_socket_path: None,pool: "l4".into(),bundle: "default".into(),@@ -347,6 +418,54 @@ mod tests {assert!(rendered.contains("worker_id: \"worker-test\""));}+ #[test]+ fn nats_credentials_require_user_and_password_together() {+ assert_eq!(NatsCredentials::from_parts(None, None), Ok(None));+ assert_eq!(+ NatsCredentials::from_parts(Some(String::new()), Some(String::new())),+ Ok(None)+ );+ assert_eq!(+ NatsCredentials::from_parts(Some("sie-worker".into()), Some("pw".into())),+ Ok(Some(NatsCredentials {+ user: "sie-worker".into(),+ password: "pw".into(),+ }))+ );+ assert!(NatsCredentials::from_parts(Some("sie-worker".into()), None).is_err());+ assert!(NatsCredentials::from_parts(None, Some("pw".into())).is_err());+ }++ #[test]+ fn worker_config_debug_redacts_the_nats_password() {+ let mut cfg = sample();+ cfg.nats_credentials = Some(NatsCredentials {+ user: "sie-worker".into(),+ password: "nats-password-secret".into(),+ });+ cfg.nats_url = Some("nats://url-user:url-secret@nats:4222".into());+ let dbg = format!("{cfg:?}");+ assert!(!dbg.contains("nats-password-secret"), "{dbg}");+ assert!(!dbg.contains("url-secret"), "{dbg}");+ assert!(dbg.contains("sie-worker"), "{dbg}");+ }++ #[test]+ fn redact_url_userinfo_hides_credentials_only() {+ assert_eq!(+ redact_url_userinfo("nats://nats-host:4222"),+ "nats://nats-host:4222"+ );+ assert_eq!(+ redact_url_userinfo("nats://user:secret@nats-host:4222"),+ "nats://<redacted>@nats-host:4222"+ );+ assert_eq!(+ redact_url_userinfo("tls://token@a:4222,nats://b:4222/x@y"),+ "tls://<redacted>@a:4222,nats://b:4222/x@y"+ );+ }+#[test]fn stream_and_consumer_names_match_gateway_contract() {let c = sample();diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rsindex ef2053ad1..e564bf3a4 100644--- a/packages/sie_server_sidecar/src/config_subscriber.rs+++ b/packages/sie_server_sidecar/src/config_subscriber.rs@@ -419,6 +419,30 @@ fn notification_is_stale(epoch: u64, current_epoch: u64) -> bool {epoch < current_epoch || (epoch == current_epoch && epoch != 0)}+/// Why `msg` did not come from a plain client publish, or `None` when it did.+///+/// sie-config publishes config notifications, and the gateway publishes+/// cancel signals, with neither a reply subject nor `Nats-` headers. A NATS+/// user that may manage JetStream streams or consumers can make the server+/// itself deliver stored bytes to any subject, past that user's publish+/// permissions: stream republish and direct-get replies carry+/// `Nats-Stream`/`Nats-Sequence` headers, and consumer deliveries carry a+/// `$JS.ACK` reply subject. Dropping those keeps these subjects limited to the+/// NATS users allowed to publish on them.+pub fn server_originated(msg: &async_nats::Message) -> Option<&'static str> {+ if msg.reply.is_some() {+ return Some("reply subject set");+ }+ let has_server_header = msg.headers.as_ref().is_some_and(|headers| {+ headers.iter().any(|(name, _)| {+ let name: &str = name.as_ref();+ name.get(..5)+ .is_some_and(|prefix| prefix.eq_ignore_ascii_case("nats-"))+ })+ });+ has_server_header.then_some("JetStream header present")+}+fn record_delta(telemetry: &SidecarTelemetry,kind: &str,@@ -551,6 +575,15 @@ pub fn spawn(subscribe_delay = next_retry_delay(subscribe_delay);break;};+ if let Some(reason) = server_originated(&msg) {+ warn!(+ subject = %subject,+ reason,+ "worker-config: dropping notification that was not published directly by a client"+ );+ record_delta(&runtime.telemetry, "unknown", "rejected_untrusted", None);+ continue;+ }let notification: ConfigNotification = match serde_json::from_slice(&msg.payload) {Ok(n) => n,Err(e) => {@@ -852,6 +885,48 @@ mod tests {use tokio::net::UnixListener;use tokio::sync::Mutex;+ fn config_message(+ reply: Option<&str>,+ headers: Option<async_nats::HeaderMap>,+ ) -> async_nats::Message {+ async_nats::Message {+ subject: "sie.config.models.default".into(),+ reply: reply.map(Into::into),+ payload: Default::default(),+ headers,+ status: None,+ description: None,+ length: 0,+ }+ }++ #[test]+ fn server_originated_accepts_only_plain_client_publishes() {+ assert_eq!(server_originated(&config_message(None, None)), None);++ let mut app_headers = async_nats::HeaderMap::new();+ app_headers.insert("traceparent", "00-abc-def-01");+ assert_eq!(+ server_originated(&config_message(None, Some(app_headers))),+ None+ );++ assert!(server_originated(&config_message(+ Some("$JS.ACK.WORK_x.pushc.1.1.1.1.0"),+ None+ ))+ .is_some());++ for name in ["Nats-Stream", "nats-sequence", "NATS-SUBJECT"] {+ let mut headers = async_nats::HeaderMap::new();+ headers.insert(name, "WORK_x");+ assert!(+ server_originated(&config_message(None, Some(headers))).is_some(),+ "{name}"+ );+ }+ }+fn notification(producer_id: &str,bundle_id: &str,diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex b72a7d9c4..a3d906ada 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -258,6 +258,7 @@ struct GenerateDeliveryLogContext {work_item_id: String,request_id: String,model_id: String,+ reply_subject: String,delivery: DeliveryContext,}@@ -362,6 +363,22 @@ fn caller_item_id_from_value(value: &MsgValue) -> Option<String> {/// True if `reply_subject` is acceptable for use on a `WorkItem`./// Empty is allowed (fire-and-forget). Non-empty subjects must start/// with `_INBOX.` so malicious producers can't redirect results.+/// The first `Nats-` header on a work delivery other than `Nats-Msg-Id`.+///+/// The gateway publishes work with at most `Nats-Msg-Id`. The NATS server adds+/// other `Nats-` headers when it copies stored messages into a work stream on+/// a user's behalf, past that user's publish permissions: a stream republish+/// adds `Nats-Stream`, and a stream source adds `Nats-Stream-Source`.+pub fn unexpected_work_header(headers: Option<&async_nats::HeaderMap>) -> Option<String> {+ headers?.iter().find_map(|(name, _)| {+ let name: &str = name.as_ref();+ let nats_header = name+ .get(..5)+ .is_some_and(|prefix| prefix.eq_ignore_ascii_case("nats-"));+ (nats_header && !name.eq_ignore_ascii_case("Nats-Msg-Id")).then(|| name.to_string())+ })+}+pub(crate) fn reply_subject_is_safe(reply_subject: &str) -> bool {reply_subject.is_empty() || reply_subject.starts_with(INBOX_PREFIX)}@@ -1207,6 +1224,22 @@ impl Dispatcher {self.runtime_state.telemetry.nats_received(msg.info().ok().map(|info| info.delivered as u64));+ if let Some(header) = unexpected_work_header(msg.headers.as_ref()) {+ warn!(+ subject = %msg.subject,+ header = %header,+ "rejecting work the NATS server copied from another stream — ACKing to drop",+ );+ if let Err(e) = ack(+ &Delivery::Nats(msg, admission_permit, None),+ &self.runtime_state.telemetry,+ )+ .await+ {+ warn!(error = %e, "ack failed on drop");+ }+ continue;+ }// Source of truth for routing is the NATS subject (JetStream// already used it to dispatch to this consumer). If the subject// doesn't yield a model_id, we can't trust the payload either,@@ -1931,6 +1964,7 @@ impl Dispatcher {work_item_id: wi.work_item_id.clone(),request_id: wi.request_id.clone(),model_id: model_id.clone(),+ reply_subject: wi.reply_subject.clone(),delivery,});let executed_bundle_config_hash: Arc<str> = Arc::from(wi.bundle_config_hash.clone());@@ -4329,6 +4363,11 @@ async fn handle_generate_event() -> Result<(), DispatchError> {match event.kind.as_str() {"publish" => {+ if event.reply_subject != delivery_log.reply_subject {+ return Err(DispatchError::Ipc(IpcError::Server(+ "generation publish reply_subject mismatch".to_string(),+ )));+ }let payload =stamp_generate_execution_hash(event.payload, executed_bundle_config_hash)?;publisher.publish_raw(&event.reply_subject, payload).await?;@@ -6386,6 +6425,64 @@ mod tests {/// Far longer than any readiness deadline the tests use.const STALLED_PROBE: Duration = Duration::from_secs(1_000_000);+ #[tokio::test]+ async fn generation_publish_to_a_subject_other_than_the_work_item_reply_is_refused() {+ let client = async_nats::ConnectOptions::new()+ .retry_on_initial_connect()+ .connect("nats://127.0.0.1:1")+ .await+ .expect("an offline client needs no server");+ let telemetry = crate::observability::metrics::SidecarTelemetry::default();+ let publisher = Arc::new(WorkPublisher::new(+ client.clone(),+ "worker-test",+ telemetry.clone(),+ ));+ let message = Message {+ message: async_nats::Message {+ subject: "sie.work.test".into(),+ reply: None,+ payload: Default::default(),+ headers: None,+ status: None,+ description: None,+ length: 0,+ },+ context: async_nats::jetstream::new(client),+ };+ let delivery = DeliveryContext::from_message(&message);+ let delivery_log = Arc::new(GenerateDeliveryLogContext {+ work_item_id: "wi-1".to_string(),+ request_id: "req-1".to_string(),+ model_id: "model".to_string(),+ reply_subject: "_INBOX.router.req-1".to_string(),+ delivery,+ });+ for subject in ["$JS.API.STREAM.CREATE.X", "sie.config.models._all", ""] {+ let result = handle_generate_event(+ GenerateEvent {+ kind: "publish".to_string(),+ reply_subject: subject.to_string(),+ payload: Vec::new(),+ delay_ms: None,+ error: None,+ },+ Arc::clone(&publisher),+ telemetry.clone(),+ Arc::new(AtomicBool::new(false)),+ Arc::new(QueuedMessage::new(message.clone(), None)),+ Arc::clone(&delivery_log),+ "",+ )+ .await;+ let error = result.expect_err(subject).to_string();+ assert!(+ error.contains("reply_subject mismatch"),+ "{subject}: {error}"+ );+ }+ }+/// A NATS delivery whose ACK, NAK and progress calls fail: it has no/// reply subject and its client never reaches a server.async fn unacknowledgeable_nats_delivery() -> Delivery {@@ -7067,6 +7164,24 @@ mod tests {);}+ #[test]+ fn unexpected_work_header_allows_only_the_gateway_message_id() {+ assert_eq!(unexpected_work_header(None), None);+ let mut gateway = async_nats::HeaderMap::new();+ gateway.insert("Nats-Msg-Id", "req-1");+ gateway.insert("traceparent", "00-abc-def-01");+ assert_eq!(unexpected_work_header(Some(&gateway)), None);+ for name in ["Nats-Stream", "Nats-Stream-Source", "nats-subject"] {+ let mut copied = async_nats::HeaderMap::new();+ copied.insert(name, "x");+ assert_eq!(+ unexpected_work_header(Some(&copied)).as_deref(),+ Some(name),+ "{name}"+ );+ }+ }+#[test]fn reply_subject_is_safe_rules() {assert!(reply_subject_is_safe(""));diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex 70affca2e..21c9588c6 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -351,8 +351,14 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {.nats_url.as_deref().context("SIE_NATS_URL is required for the NATS ingest mode")?;- let (nats_client, jetstream) = connect(nats_url).await.context("connect NATS")?;- info!(nats = %nats_url, "NATS connected");+ let (nats_client, jetstream) = connect(nats_url, config.nats_credentials.as_ref())+ .await+ .context("connect NATS")?;+ info!(+ nats = %crate::config::redact_url_userinfo(nats_url),+ user = config.nats_credentials.as_ref().map_or("", |c| c.user.as_str()),+ "NATS connected"+ );let consumer = ensure_stream_and_consumer(&jetstream, &config).await.context("ensure NATS stream/consumer")?;@@ -1206,7 +1212,9 @@ async fn spawn_work_cancel_subscriber(}continue;};- let subject = msg.subject.to_string();+ let Some(subject) = cancel_signal_subject(&msg, "work_cancel") else {+ continue;+ };let Some((router_id, request_id)) = request_id_from_work_cancel_subject(&subject) else {debug!(subject = %subject, "work-cancel: ignoring malformed subject");continue;@@ -1252,7 +1260,9 @@ fn spawn_generation_cancel_subscriber(warn!("generation: cancel subscription ended");return;};- let subject = msg.subject.to_string();+ let Some(subject) = cancel_signal_subject(&msg, "cancel") else {+ continue;+ };if let Some((router_id, request_id)) =request_id_from_generation_cancel_subject(&subject){@@ -1324,7 +1334,9 @@ async fn spawn_batch_direct_cancel_subscriber(}continue;};- let subject = msg.subject.to_string();+ let Some(subject) = cancel_signal_subject(&msg, "batch_cancel") else {+ continue;+ };let Some(request_id) =request_id_from_batch_cancel_subject(&subject, &worker_id)else {@@ -1343,6 +1355,21 @@ async fn spawn_batch_direct_cancel_subscriber(}))}+/// The subject of a cancel signal, or `None` when the NATS server delivered it+/// on another user's behalf.+fn cancel_signal_subject(msg: &async_nats::Message, kind: &'static str) -> Option<String> {+ if let Some(reason) = config_subscriber::server_originated(msg) {+ warn!(+ subject = %msg.subject,+ kind,+ reason,+ "dropping cancel signal that was not published directly by a client"+ );+ return None;+ }+ Some(msg.subject.to_string())+}+fn request_id_from_cancel_subject(subject: &str) -> Option<String> {let mut parts = subject.splitn(3, '.');match (parts.next(), parts.next(), parts.next()) {@@ -1878,6 +1905,34 @@ mod tests {}}+ #[test]+ fn cancel_signal_subject_drops_server_deliveries() {+ let message =+ |reply: Option<&str>, headers: Option<async_nats::HeaderMap>| async_nats::Message {+ subject: "work_cancel.gw.req-1".into(),+ reply: reply.map(Into::into),+ payload: bytes::Bytes::new(),+ headers,+ status: None,+ description: None,+ length: 0,+ };+ assert_eq!(+ cancel_signal_subject(&message(None, None), "work_cancel").as_deref(),+ Some("work_cancel.gw.req-1")+ );+ assert_eq!(+ cancel_signal_subject(&message(Some("$JS.ACK.S.c.1.1.1.1.0"), None), "work_cancel"),+ None+ );+ let mut headers = async_nats::HeaderMap::new();+ headers.insert("Nats-Stream", "COPY");+ assert_eq!(+ cancel_signal_subject(&message(None, Some(headers)), "work_cancel"),+ None+ );+ }+#[test]fn cancel_subject_parser_extracts_request_id() {assert_eq!(diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rsindex b6224bb38..432fc2569 100644--- a/packages/sie_server_sidecar/src/main.rs+++ b/packages/sie_server_sidecar/src/main.rs@@ -10,7 +10,7 @@ use anyhow::Context;use clap::Parser;use tracing::{error, info, warn};-use sie_server_sidecar::config::WorkerConfig;+use sie_server_sidecar::config::{NatsCredentials, WorkerConfig};use sie_server_sidecar::config_subscriber::trusted_producers_from_env;use sie_server_sidecar::dispatcher::default_max_concurrent_batches;use sie_server_sidecar::{run, run_local};@@ -29,8 +29,9 @@ struct Cli {#[arg(long, env = "SIE_SIDECAR_LOCAL_SOCKET")]local_socket: Option<String>,- /// Required for `--ingest nats`; unused in local mode.- #[arg(long, env = "SIE_NATS_URL")]+ /// Required for `--ingest nats`; unused in local mode. Credentials come+ /// from `SIE_NATS_USER` / `SIE_NATS_PASSWORD`, never from the URL.+ #[arg(long, env = "SIE_NATS_URL", hide_env_values = true)]nats_url: Option<String>,#[arg(long, env = "SIE_POOL")]@@ -210,8 +211,10 @@ async fn main() -> anyhow::Result<()> {{CONFIG_SERVICE_TOKEN_ENV} to sie-config's read-scoped token (SIE_CONFIG_READ_TOKEN)");}+ let nats_credentials = NatsCredentials::from_env().map_err(anyhow::Error::msg)?;let config = WorkerConfig {nats_url: cli.nats_url,+ nats_credentials,local_socket_path: cli.local_socket.map(Into::into),pool,bundle,diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex 52522309b..a780ef9e7 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -18,7 +18,7 @@ use futures_util::TryStreamExt;use thiserror::Error;use tracing::{debug, info, warn};-use crate::config::WorkerConfig;+use crate::config::{NatsCredentials, WorkerConfig};use crate::subject::subjects_overlap;/// Default consumer parameters. Must match the gateway's stream creator@@ -172,9 +172,34 @@ pub enum NatsSetupError {},}+/// Inbox prefix of the sidecar's JetStream API replies and pull deliveries.+/// It differs from the gateway's `_INBOX`, where workers publish results, so a+/// NATS user can be allowed to publish results without reading gateway inboxes.+pub const WORKER_INBOX_PREFIX: &str = "_INBOX_WORKER";+/// Connect to NATS and return a JetStream context.-pub async fn connect(nats_url: &str) -> Result<(async_nats::Client, JsContext), NatsSetupError> {- let client = async_nats::connect(nats_url)+pub async fn connect(+ nats_url: &str,+ credentials: Option<&NatsCredentials>,+) -> Result<(async_nats::Client, JsContext), NatsSetupError> {+ let mut options = async_nats::ConnectOptions::new()+ .custom_inbox_prefix(WORKER_INBOX_PREFIX)+ .event_callback(|event| async move {+ match event {+ async_nats::Event::ServerError(error) => {+ warn!(error = %error, "NATS server error");+ }+ async_nats::Event::ClientError(error) => {+ warn!(error = %error, "NATS client error");+ }+ other => info!(event = %other, "NATS event"),+ }+ });+ if let Some(credentials) = credentials {+ options = options.user_and_password(credentials.user.clone(), credentials.password.clone());+ }+ let client = options+ .connect(nats_url).await.map_err(|source| NatsSetupError::Connect { source })?;let js = async_nats::jetstream::new(client.clone());@@ -922,6 +947,7 @@ mod tests {fn config_produces_expected_names() {let cfg = WorkerConfig {nats_url: Some(String::new()),+ nats_credentials: None,local_socket_path: None,pool: "default".into(),bundle: "b".into(),diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rsindex 6940f6c1f..e8f6ff7e7 100644--- a/packages/sie_server_sidecar/tests/integration_smoke.rs+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs@@ -3262,12 +3262,13 @@ async fn ensure_paths_reconcile_stream_discard_policy_to_new() {let nats = NatsHarness::start().await;eprintln!("nats: {} (port {})", nats.url, nats.port);- let (_client, js) = sie_server_sidecar::nats_consumer::connect(&nats.url)+ let (_client, js) = sie_server_sidecar::nats_consumer::connect(&nats.url, None).await.expect("connect JetStream");let config = sie_server_sidecar::config::WorkerConfig {nats_url: Some(nats.url.clone()),+ nats_credentials: None,local_socket_path: None,pool: "discardsmoke".into(),bundle: "default".into(),diff --git a/packages/sie_server_sidecar/tests/nats_auth.rs b/packages/sie_server_sidecar/tests/nats_auth.rsnew file mode 100644index 000000000..e4f272dd8--- /dev/null+++ b/packages/sie_server_sidecar/tests/nats_auth.rs@@ -0,0 +1,474 @@+//! Integration test: the sidecar on an authenticated NATS server.+//!+//! Runs `nats-server` with the configuration the Helm chart renders by+//! default (`tools/ci/fixtures/sie-cluster-nats.conf`, which+//! `tools/ci/tests/test_helm_render.py` keeps equal to the chart). Skips when+//! `nats-server` is not on `PATH`, unless `NATS_URL` is set as in CI, where a+//! missing binary fails the test.++use std::net::TcpStream;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::time::Duration;++use async_nats::jetstream;+use async_nats::jetstream::message::PublishMessage;+use async_nats::jetstream::stream::{+ Config as StreamConfig, Republish, Source, StorageType, SubjectTransform,+};+use futures_util::StreamExt;+use sie_server_sidecar::config::{NatsCredentials, WorkerConfig};+use sie_server_sidecar::config_subscriber::server_originated;+use sie_server_sidecar::dispatcher::unexpected_work_header;+use sie_server_sidecar::nats_consumer;++struct Passwords {+ config: String,+ gateway: String,+ worker: String,+}++fn random_password() -> String {+ format!("p{}", uuid::Uuid::new_v4().simple())+}++struct NatsServer {+ child: Child,+ url: String,+ passwords: Passwords,+ dir: tempfile::TempDir,+}++impl Drop for NatsServer {+ fn drop(&mut self) {+ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++fn nats_server_binary() -> Option<PathBuf> {+ let paths = std::env::var_os("PATH")?;+ std::env::split_paths(&paths)+ .map(|dir| dir.join("nats-server"))+ .find(|path| path.is_file())+}++async fn start_nats() -> Option<NatsServer> {+ let Some(binary) = nats_server_binary() else {+ assert!(+ std::env::var_os("NATS_URL").is_none(),+ "nats-server must be on PATH when NATS_URL is set"+ );+ eprintln!("skipping: nats-server not on PATH");+ return None;+ };+ let config =+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/ci/fixtures/sie-cluster-nats.conf");+ let dir = tempfile::tempdir().expect("tempdir");+ let log = std::fs::File::create(dir.path().join("nats.log")).expect("log file");+ let passwords = Passwords {+ config: random_password(),+ gateway: random_password(),+ worker: random_password(),+ };+ let child = Command::new(binary)+ .arg("-c")+ .arg(&config)+ .args(["-a", "127.0.0.1", "-p", "-1", "-m", "-1"])+ .arg("--ports_file_dir")+ .arg(dir.path())+ .arg("-sd")+ .arg(dir.path().join("jetstream"))+ .arg("-P")+ .arg(dir.path().join("nats.pid"))+ .env("SERVER_NAME", "sie-sidecar-auth-test")+ .env("SIE_NATS_AUTH_CONFIG_PASSWORD", &passwords.config)+ .env("SIE_NATS_AUTH_GATEWAY_PASSWORD", &passwords.gateway)+ .env("SIE_NATS_AUTH_WORKER_PASSWORD", &passwords.worker)+ .stdout(Stdio::null())+ .stderr(log)+ .spawn()+ .expect("start nats-server");+ let mut server = NatsServer {+ child,+ url: String::new(),+ passwords,+ dir,+ };+ for _ in 0..600 {+ if let Some(url) = listening_url(server.dir.path()) {+ server.url = url;+ return Some(server);+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ let log = std::fs::read_to_string(server.dir.path().join("nats.log")).unwrap_or_default();+ panic!("nats-server did not start:\n{log}");+}++/// The client URL from the `*.ports` file nats-server writes once it listens.+fn listening_url(dir: &Path) -> Option<String> {+ let ports = std::fs::read_dir(dir)+ .ok()?+ .filter_map(Result::ok)+ .find(|entry| entry.path().extension().is_some_and(|ext| ext == "ports"))?;+ let ports: serde_json::Value =+ serde_json::from_slice(&std::fs::read(ports.path()).ok()?).ok()?;+ let url = ports["nats"][0].as_str()?.to_string();+ let address = url.trim_start_matches("nats://").to_string();+ TcpStream::connect(address).ok().map(|_| url)+}++async fn connect_as(url: &str, user: &str, password: &str) -> async_nats::Client {+ async_nats::ConnectOptions::new()+ .user_and_password(user.to_string(), password.to_string())+ .connect(url)+ .await+ .unwrap_or_else(|e| panic!("connect as {user}: {e}"))+}++fn worker_credentials(nats: &NatsServer) -> NatsCredentials {+ NatsCredentials {+ user: "sie-worker".to_string(),+ password: nats.passwords.worker.clone(),+ }+}++fn worker_config(nats: &NatsServer) -> WorkerConfig {+ WorkerConfig {+ nats_url: Some(nats.url.clone()),+ nats_credentials: Some(worker_credentials(nats)),+ local_socket_path: None,+ pool: "authpool".into(),+ bundle: "default".into(),+ ipc_socket_path: PathBuf::from("/tmp/auth-test.sock"),+ ipc_socket_paths: vec![PathBuf::from("/tmp/auth-test.sock")],+ ipc_pool_size: 1,+ ipc_request_timeout_s: 60,+ model_ready_timeout_s: 900,+ payload_store_url: None,+ gateway_url: None,+ gateway_api_key: None,+ pool_admission_enabled: false,+ pool_admission_check_interval_ms: 5_000,+ pool_admission_pause_ms: 1_000,+ pool_admission_stale_after_ms: 30_000,+ probe_port: 9095,+ worker_id: "auth-worker-0".into(),+ ping_interval_ms: 2000,+ ready_stale_mult: 3,+ machine_profile: "l4".into(),+ gpu_count: 1,+ bundle_config_hash: String::new(),+ config_service_url: None,+ config_service_token: None,+ config_poll_interval_ms: 30_000,+ config_full_export_interval_ms: 300_000,+ nats_config_trusted_producers: vec!["sie-config".into()],+ health_publish_interval_ms: 5_000,+ }+}++async fn nothing_arrives(subscriber: &mut async_nats::Subscriber) -> bool {+ tokio::time::timeout(Duration::from_millis(500), subscriber.next())+ .await+ .is_err()+}++#[tokio::test]+async fn worker_user_consumes_work_and_returns_results() {+ let Some(nats) = start_nats().await else {+ return;+ };+ let config = worker_config(&nats);+ let (worker, js) = nats_consumer::connect(&nats.url, config.nats_credentials.as_ref())+ .await+ .expect("connect as sie-worker");+ let consumer = nats_consumer::ensure_stream_and_consumer(&js, &config)+ .await+ .expect("the worker user provisions its pool stream and consumer");+ nats_consumer::ensure_worker_stream_and_consumer(&js, &config)+ .await+ .expect("the worker user provisions its direct-dispatch stream and consumer");++ let gateway = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let mut results = gateway+ .subscribe("_INBOX.gateway-auth-test.>")+ .await+ .expect("subscribe");+ gateway.flush().await.expect("gateway flush");+ jetstream::new(gateway.clone())+ .publish("sie.work.authpool.l4.default.model", "work".into())+ .await+ .expect("publish work")+ .await+ .expect("work stored");++ let mut messages = consumer.messages().await.expect("pull");+ let work = tokio::time::timeout(Duration::from_secs(5), messages.next())+ .await+ .expect("work delivered")+ .expect("pull stream open")+ .expect("work message");+ assert_eq!(work.payload.as_ref(), b"work");+ work.ack().await.expect("ack");++ worker+ .publish("_INBOX.gateway-auth-test.req-1", "result".into())+ .await+ .expect("publish result");+ worker.flush().await.expect("worker flush");+ let result = tokio::time::timeout(Duration::from_secs(5), results.next())+ .await+ .expect("result delivered")+ .expect("subscription open");+ assert_eq!(result.payload.as_ref(), b"result");+}++#[tokio::test]+async fn worker_user_is_refused_outside_its_subjects() {+ let Some(nats) = start_nats().await else {+ return;+ };+ let config = worker_config(&nats);+ let (worker, js) = nats_consumer::connect(&nats.url, config.nats_credentials.as_ref())+ .await+ .expect("connect as sie-worker");+ nats_consumer::ensure_stream_and_consumer(&js, &config)+ .await+ .expect("pool stream");++ let gateway = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let mut config_deltas = gateway+ .subscribe("sie.config.models._all")+ .await+ .expect("subscribe");+ let mut gateway_results = worker+ .subscribe("_INBOX.gateway-auth-test.>")+ .await+ .expect("subscribe request is sent");+ gateway.flush().await.expect("gateway flush");+ worker.flush().await.expect("worker flush");++ worker+ .publish("sie.config.models._all", "{}".into())+ .await+ .expect("publish is sent");+ worker+ .publish("sie.work.authpool.l4.default.model", "forged".into())+ .await+ .expect("publish is sent");+ worker+ .publish("cancel.gateway-auth-test.req-1", "".into())+ .await+ .expect("publish is sent");+ let other_worker = nats_consumer::connect(&nats.url, Some(&worker_credentials(&nats)))+ .await+ .expect("second worker")+ .0;+ other_worker+ .publish("_INBOX.gateway-auth-test.req-2", "result".into())+ .await+ .expect("publish result");+ other_worker.flush().await.expect("flush");+ worker.flush().await.expect("worker flush");++ assert!(+ nothing_arrives(&mut config_deltas).await,+ "config subject is sie-config only"+ );+ assert!(+ nothing_arrives(&mut gateway_results).await,+ "workers cannot subscribe to gateway inboxes"+ );+ let stream = js+ .get_stream("WORK_POOL_authpool")+ .await+ .expect("stream info");+ assert_eq!(+ stream.cached_info().state.messages,+ 0,+ "workers cannot publish work"+ );+ assert!(js.delete_stream("WORK_POOL_authpool").await.is_err());+ assert!(js+ .get_stream("WORK_POOL_authpool")+ .await+ .expect("stream still exists")+ .purge()+ .await+ .is_err());+}++async fn next_message(subscriber: &mut async_nats::Subscriber) -> async_nats::Message {+ tokio::time::timeout(Duration::from_secs(5), subscriber.next())+ .await+ .expect("message delivered")+ .expect("subscription open")+}++#[tokio::test]+async fn deliveries_the_server_makes_for_a_worker_are_recognised() {+ let Some(nats) = start_nats().await else {+ return;+ };+ let config = worker_config(&nats);+ let (worker, js) = nats_consumer::connect(&nats.url, config.nats_credentials.as_ref())+ .await+ .expect("connect as sie-worker");+ let consumer = nats_consumer::ensure_stream_and_consumer(&js, &config)+ .await+ .expect("pool stream");+ let gateway = connect_as(&nats.url, "sie-gateway", &nats.passwords.gateway).await;+ let work_subject = "sie.work.authpool.l4.default.model";++ jetstream::new(gateway.clone())+ .send_publish(+ work_subject,+ PublishMessage::build()+ .message_id("req-1")+ .payload("gateway".into()),+ )+ .await+ .expect("publish work")+ .await+ .expect("work stored");++ js.create_stream(StreamConfig {+ name: "COPY_REPUBLISH".into(),+ subjects: vec!["sie.health.copy".into()],+ storage: StorageType::Memory,+ republish: Some(Republish {+ source: "sie.health.copy".into(),+ destination: work_subject.into(),+ headers_only: false,+ }),+ ..Default::default()+ })+ .await+ .expect("the worker user may create streams");+ worker+ .publish("sie.health.copy", "republished".into())+ .await+ .expect("publish");++ js.create_stream(StreamConfig {+ name: "COPY_SOURCE".into(),+ subjects: vec!["sie.health.source".into()],+ storage: StorageType::Memory,+ ..Default::default()+ })+ .await+ .expect("the worker user may create streams");+ let mut pool_config = js+ .get_stream("WORK_POOL_authpool")+ .await+ .expect("pool stream")+ .cached_info()+ .config+ .clone();+ pool_config.sources = Some(vec![Source {+ name: "COPY_SOURCE".into(),+ subject_transforms: vec![SubjectTransform {+ source: "sie.health.source".into(),+ destination: work_subject.into(),+ }],+ ..Default::default()+ }]);+ js.update_stream(pool_config)+ .await+ .expect("the worker user may update streams");+ worker+ .publish("sie.health.source", "sourced".into())+ .await+ .expect("publish");+ worker.flush().await.expect("worker flush");++ let mut messages = consumer.messages().await.expect("pull");+ let mut rejected = std::collections::BTreeMap::new();+ for _ in 0..3 {+ let message = tokio::time::timeout(Duration::from_secs(5), messages.next())+ .await+ .expect("work delivered")+ .expect("pull stream open")+ .expect("work message");+ rejected.insert(+ String::from_utf8(message.payload.to_vec()).expect("utf-8"),+ unexpected_work_header(message.headers.as_ref()),+ );+ message.ack().await.expect("ack");+ }+ assert_eq!(+ rejected["gateway"], None,+ "gateway work carries Nats-Msg-Id only"+ );+ assert!(rejected["republished"]+ .as_deref()+ .is_some_and(|header| header.starts_with("Nats-")));+ assert_eq!(rejected["sourced"].as_deref(), Some("Nats-Stream-Source"));++ for (index, subject) in [+ "work_cancel.gateway-auth-test.req-9",+ "cancel.gateway-auth-test.req-9",+ "batch_cancel.gateway-auth-test.auth-worker-0.req-9",+ ]+ .into_iter()+ .enumerate()+ {+ let mut cancels = worker.subscribe(subject).await.expect("subscribe");+ worker.flush().await.expect("worker flush");+ let source = format!("sie.health.cancel{index}");+ js.create_stream(StreamConfig {+ name: format!("COPY_CANCEL_{index}"),+ subjects: vec![source.clone()],+ storage: StorageType::Memory,+ republish: Some(Republish {+ source: source.clone(),+ destination: subject.into(),+ headers_only: false,+ }),+ ..Default::default()+ })+ .await+ .expect("the worker user may create streams");+ worker.publish(source, "".into()).await.expect("publish");+ worker.flush().await.expect("worker flush");+ assert!(+ server_originated(&next_message(&mut cancels).await).is_some(),+ "{subject} republished for a worker"+ );+ gateway.publish(subject, "".into()).await.expect("publish");+ gateway.flush().await.expect("gateway flush");+ assert_eq!(+ server_originated(&next_message(&mut cancels).await),+ None,+ "{subject} from the gateway"+ );+ }+}++#[test]+fn help_does_not_print_nats_secrets() {+ let url_password = random_password();+ let password = random_password();+ let output = Command::new(env!("CARGO_BIN_EXE_sie-server-sidecar"))+ .arg("--help")+ .env(+ "SIE_NATS_URL",+ format!("nats://url-user:{url_password}@nats:4222"),+ )+ .env("SIE_NATS_USER", "sie-worker")+ .env("SIE_NATS_PASSWORD", &password)+ .output()+ .expect("run --help");+ assert!(output.status.success());+ let help = String::from_utf8_lossy(&output.stdout);+ assert!(+ !help.contains(&url_password),+ "--help printed the URL password"+ );+ assert!(+ !help.contains(&password),+ "--help printed SIE_NATS_PASSWORD"+ );+}diff --git a/tools/ci/cpu_stack_smoke.py b/tools/ci/cpu_stack_smoke.pyindex d716f00ff..d71cd15c8 100644--- a/tools/ci/cpu_stack_smoke.py+++ b/tools/ci/cpu_stack_smoke.py@@ -2,6 +2,7 @@from __future__ import annotations+import asyncioimport jsonimport osimport secrets@@ -13,11 +14,13 @@ import urllib.requestimport uuidfrom pathlib import Path+import natsfrom sie_sdk import SIEClientfrom tools.ci.live_sdk import smoke_python, wait_for_apiSERVICES = ("sie-config", "sie-gateway", "sie-server-sidecar", "sie-mcp", "sie-server-rust-cpu")+NATS_SERVER_CONFIG = Path(__file__).resolve().parent / "fixtures" / "sie-cluster-nats.conf"def docker(*args: str, check: bool = True) -> str:@@ -126,6 +129,17 @@ def require_gateway_catalog(gateway_url: str, catalog: set[str]) -> None:print(f"Gateway loaded the {len(catalog)}-model sie-config catalog through the read token.")+async def assert_nats_refuses_anonymous(url: str) -> None:+ try:+ client = await nats.connect(url, allow_reconnect=False, max_reconnect_attempts=0, connect_timeout=5)+ except Exception as error:+ if "authorization" not in str(error).lower():+ raise+ return+ await client.close()+ raise RuntimeError("NATS accepted an anonymous connection")++def build_images(registry: str, revision: str) -> None:common = ["--registry", registry, "--version", "0.0.0", "--source-revision", revision]commands = [["build-server", "--platform", "cpu", "--bundle", "default", *common]]@@ -154,11 +168,14 @@ def main() -> None:command: tuple[str, ...] = (),port: int | None = None,shared_ipc: bool = False,+ volumes: tuple[str, ...] = (),) -> str:container = f"{network}-{name}"args = ["run", "--detach", "--name", container, "--network", network, "--network-alias", name]if port is not None:args += ["-p", f"127.0.0.1::{port}"]+ for volume in volumes:+ args += ["-v", volume]if shared_ipc:args += ["--user", "0:0", "-v", f"{ipc}:/var/run/sie"]for key, value in (env or {}).items():@@ -173,11 +190,30 @@ def main() -> None:def image(service: str) -> str:return f"{registry}/{service}:v0.0.0"+ nats_passwords = {component: f"p{secrets.token_hex(24)}" for component in ("config", "gateway", "worker")}++ def nats_client_env(component: str) -> dict[str, str]:+ return {+ "SIE_NATS_URL": "nats://nats:4222",+ "SIE_NATS_USER": f"sie-{component}",+ "SIE_NATS_PASSWORD": nats_passwords[component],+ }+try:- start("nats", "nats:2.11.8-alpine", command=("-js",))+ nats_url = start(+ "nats",+ "nats:2.11.8-alpine",+ env={+ "SERVER_NAME": "nats",+ **{f"SIE_NATS_AUTH_{name.upper()}_PASSWORD": value for name, value in nats_passwords.items()},+ },+ command=("-c", "/etc/nats/sie-cluster.conf", "-P", "/tmp/nats.pid"),+ port=4222,+ volumes=(f"{NATS_SERVER_CONFIG}:/etc/nats/sie-cluster.conf:ro",),+ ).replace("http://", "nats://")read_token = secrets.token_urlsafe(32)config_env = {- "SIE_NATS_URL": "nats://nats:4222",+ **nats_client_env("config"),"SIE_DEPLOYMENT_ENV": "production","SIE_ADMIN_TOKEN": secrets.token_urlsafe(32),"SIE_CONFIG_READ_TOKEN": read_token,@@ -204,7 +240,7 @@ def main() -> None:)wait_for_api(worker_url)gateway_env = {- "SIE_NATS_URL": "nats://nats:4222",+ **nats_client_env("gateway"),"SIE_CONFIG_SERVICE_URL": "http://config:8080","SIE_CONFIG_SERVICE_TOKEN": read_token,"SIE_GATEWAY_HEALTH_MODE": "nats",@@ -227,7 +263,7 @@ def main() -> None:port=9095,env={**worker_env,- "SIE_NATS_URL": "nats://nats:4222",+ **nats_client_env("worker"),"SIE_WORKER_ID": "cpu-smoke","SIE_GATEWAY_URL": "http://gateway:8080","SIE_CONFIG_SERVICE_URL": "http://config:8080",@@ -240,6 +276,7 @@ def main() -> None:require_gateway_catalog(gateway_url, catalog)wait_for_api(gateway_url)smoke_python(gateway_url)+ asyncio.run(assert_nats_refuses_anonymous(nats_url))mcp_url = start("mcp",image("sie-mcp"),@@ -260,7 +297,10 @@ def main() -> None:)wait_health(f"{rust_url}/healthz")docker("exec", f"{network}-worker", "python", "-c", IPC_SMOKE)- print("CPU gateway/config/worker/sidecar queue requests, MCP health and Rust worker IPC passed.")+ print(+ "CPU gateway/config/worker/sidecar queue requests over authenticated NATS, "+ "MCP health and Rust worker IPC passed."+ )finally:for container in reversed(containers):(logs / f"{container}.log").write_text(docker("logs", container, check=False))diff --git a/tools/ci/fixtures/sie-cluster-nats.conf b/tools/ci/fixtures/sie-cluster-nats.confnew file mode 100644index 000000000..a3f2b74d1--- /dev/null+++ b/tools/ci/fixtures/sie-cluster-nats.conf@@ -0,0 +1,89 @@+{+ "authorization": {+ "users": [+ {+ "password": $SIE_NATS_AUTH_CONFIG_PASSWORD,+ "permissions": {+ "publish": {+ "allow": [+ "sie.config.models.>"+ ]+ },+ "subscribe": {+ "deny": [+ ">"+ ]+ }+ },+ "user": "sie-config"+ },+ {+ "password": $SIE_NATS_AUTH_GATEWAY_PASSWORD,+ "permissions": {+ "publish": {+ "allow": [+ "sie.work.>",+ "sie.dlq.>",+ "cancel.>",+ "work_cancel.>",+ "batch_cancel.>",+ "$JS.API.STREAM.INFO.*",+ "$JS.API.STREAM.CREATE.*",+ "$JS.API.STREAM.UPDATE.*",+ "$JS.API.CONSUMER.INFO.*.*"+ ]+ },+ "subscribe": {+ "allow": [+ "sie.config.models._all",+ "sie.health.>",+ "_INBOX.>",+ "$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>"+ ]+ }+ },+ "user": "sie-gateway"+ },+ {+ "password": $SIE_NATS_AUTH_WORKER_PASSWORD,+ "permissions": {+ "publish": {+ "allow": [+ "_INBOX.>",+ "sie.health.>",+ "$JS.ACK.>",+ "$JS.API.STREAM.INFO.*",+ "$JS.API.STREAM.CREATE.*",+ "$JS.API.STREAM.UPDATE.*",+ "$JS.API.CONSUMER.LIST.*",+ "$JS.API.CONSUMER.INFO.*.*",+ "$JS.API.CONSUMER.CREATE.*.>",+ "$JS.API.CONSUMER.DELETE.*.*",+ "$JS.API.CONSUMER.MSG.NEXT.*.*"+ ]+ },+ "subscribe": {+ "allow": [+ "sie.config.models.*",+ "cancel.>",+ "work_cancel.>",+ "batch_cancel.>",+ "_INBOX_WORKER.>"+ ]+ }+ },+ "user": "sie-worker"+ }+ ]+ },+ "http_port": 8222,+ "jetstream": {+ "max_file_store": 0,+ "max_memory_store": 512MB+ },+ "lame_duck_duration": "30s",+ "lame_duck_grace_period": "10s",+ "pid_file": "/var/run/nats/nats.pid",+ "port": 4222,+ "server_name": $SERVER_NAME+}diff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.pyindex 44ec7dd62..2f88a01f6 100644--- a/tools/ci/tests/test_helm_render.py+++ b/tools/ci/tests/test_helm_render.py@@ -2,9 +2,13 @@ from __future__ import annotationsimport base64import json+import osimport reimport shutil+import socketimport subprocess+import time+import urllib.requestfrom pathlib import Pathimport pytest@@ -1044,3 +1048,361 @@ def test_worker_network_policy_rejects_prefix_zero_and_near_full_port_ranges("workers": {"networkPolicy": {"enabled": True, "extraIngress": [rule]}, "pools": {"l4": {"enabled": True}}}}assert message in render_error(tmp_path, values)+++NATS_SERVER_CONFIG_FIXTURE = ROOT / "tools/ci/fixtures/sie-cluster-nats.conf"+NATS_L4_POOL = {"workers": {"pools": {"l4": {"enabled": True}}}}+NATS_CLIENTS = {+ "config": ("sie-sie-cluster-config", "config"),+ "gateway": ("sie-sie-cluster-gateway", "gateway"),+ "worker": ("sie-sie-cluster-worker-l4-default", "worker-sidecar"),+}+++def render_nats_chart(tmp_path: Path, values: dict, *extra: str) -> subprocess.CompletedProcess[str]:+ values_file = tmp_path / "nats-values.yaml"+ values_file.write_text(yaml.safe_dump(values), encoding="utf-8")+ return subprocess.run(+ [+ "mise",+ "exec",+ "--",+ "helm",+ "template",+ "sie",+ str(helm.CHART_DIR),+ "--namespace",+ "sie",+ *helm.validation_args([*extra, "-f", str(values_file)]),+ ],+ cwd=ROOT,+ capture_output=True,+ text=True,+ check=False,+ )+++def nats_documents(tmp_path: Path, values: dict, *extra: str) -> list[dict]:+ result = render_nats_chart(tmp_path, values, *extra)+ assert result.returncode == 0, result.stderr+ return [doc for doc in yaml.safe_load_all(result.stdout) if doc]+++def workload_env(docs: list[dict], workload: str, container: str) -> dict[str, dict]:+ (doc,) = [+ doc for doc in docs if doc["kind"] in {"Deployment", "StatefulSet"} and doc["metadata"]["name"] == workload+ ]+ (spec,) = [spec for spec in doc["spec"]["template"]["spec"]["containers"] if spec["name"] == container]+ return {env["name"]: env for env in spec.get("env", [])}+++def nats_server_config(docs: list[dict]) -> str:+ (config_map,) = [doc for doc in docs if doc["kind"] == "ConfigMap" and doc["metadata"]["name"] == "sie-nats-config"]+ return config_map["data"]["nats.conf"]+++def nats_auth_secrets(docs: list[dict]) -> dict[str, dict]:+ return {+ doc["metadata"]["name"]: doc+ for doc in docs+ if doc["kind"] == "Secret" and doc["metadata"]["name"].startswith("sie-nats-auth-")+ }+++def nats_client_credentials(docs: list[dict]) -> dict[str, tuple[str, dict]]:+ credentials = {}+ for component, (workload, container) in NATS_CLIENTS.items():+ env = workload_env(docs, workload, container)+ if "SIE_NATS_PASSWORD" in env:+ credentials[component] = (+ env["SIE_NATS_USER"]["value"],+ env["SIE_NATS_PASSWORD"]["valueFrom"]["secretKeyRef"],+ )+ return credentials+++def test_nats_server_config_fixture_matches_the_chart(tmp_path: Path) -> None:+ docs = nats_documents(tmp_path, {})+ assert nats_server_config(docs) == NATS_SERVER_CONFIG_FIXTURE.read_text(encoding="utf-8"), (+ "tools/ci/fixtures/sie-cluster-nats.conf must equal the nats.conf the chart renders by default; "+ "the gateway, sidecar, CPU-stack, and permission tests run nats-server with it"+ )++[email protected]("auth", [{}, {"nats": {"auth": None}}, {"nats": {"auth": {"enabled": None}}}])+def test_nats_authentication_is_on_by_default(tmp_path: Path, auth: dict) -> None:+ docs = nats_documents(tmp_path, {**NATS_L4_POOL, **auth})+ secrets = nats_auth_secrets(docs)+ assert sorted(secrets) == ["sie-nats-auth-config", "sie-nats-auth-gateway", "sie-nats-auth-worker"]+ for secret in secrets.values():+ assert secret["metadata"]["annotations"] == {"helm.sh/resource-policy": "keep"}+ assert re.fullmatch(r"[A-Za-z][A-Za-z0-9]{47}", base64.b64decode(secret["data"]["password"]).decode())+ assert nats_client_credentials(docs) == {+ component: (f"sie-{component}", {"name": f"sie-nats-auth-{component}", "key": "password"})+ for component in NATS_CLIENTS+ }+ worker = workload_env(docs, "sie-sie-cluster-worker-l4-default", "worker")+ assert not {"SIE_NATS_URL", "SIE_NATS_USER", "SIE_NATS_PASSWORD"} & set(worker)+ server_env = workload_env(docs, "sie-nats", "nats")+ for component in NATS_CLIENTS:+ assert server_env[f"SIE_NATS_AUTH_{component.upper()}_PASSWORD"]["valueFrom"]["secretKeyRef"] == {+ "name": f"sie-nats-auth-{component}",+ "key": "password",+ }+ config = nats_server_config(docs)+ for component in NATS_CLIENTS:+ assert f'"user": "sie-{component}"' in config+ assert f'"password": $SIE_NATS_AUTH_{component.upper()}_PASSWORD' in config+ assert "no_auth_user" not in config+ assert not [doc for doc in docs if "nats-box" in doc["metadata"]["name"]]+++KUBERNETES_WRITE_VERBS = {"create", "update", "patch", "delete", "deletecollection", "*"}+++def role_writes(role: dict, resource: str) -> bool:+ return any(+ {resource, "*"} & set(rule.get("resources", [])) and KUBERNETES_WRITE_VERBS & set(rule.get("verbs", []))+ for rule in role.get("rules", [])+ )++[email protected]("overlays", [(), ("values-ha.yaml",)])+def test_only_gateway_pods_hold_a_token_that_can_write_configmaps(tmp_path: Path, overlays: tuple[str, ...]) -> None:+ overlay_args = [arg for overlay in overlays for arg in ("-f", str(helm.CHART_DIR / overlay))]+ docs = nats_documents(tmp_path, {**NATS_L4_POOL, "mcpEdge": {"enabled": True}}, *overlay_args)+ assert bool(overlays) == any(+ doc["kind"] == "NetworkPolicy" and doc["metadata"]["name"].endswith("-worker") for doc in docs+ )+ roles = {doc["metadata"]["name"]: doc for doc in docs if doc["kind"] == "Role"}+ assert not [name for name, role in roles.items() if role_writes(role, "secrets")]+ writers = {+ subject["name"]+ for doc in docs+ if doc["kind"] == "RoleBinding" and role_writes(roles[doc["roleRef"]["name"]], "configmaps")+ for subject in doc["subjects"]+ if subject["kind"] == "ServiceAccount"+ }+ assert writers == {"sie-server"}+ pods = {+ doc["metadata"]["name"]: doc["spec"]["template"]["spec"]+ for doc in docs+ if doc["kind"] in {"Deployment", "StatefulSet", "DaemonSet", "Job"}+ }+ assert {"sie-sie-cluster-config", "sie-sie-cluster-mcp", "sie-sie-cluster-worker-l4-default"} <= set(pods)+ mounting = sorted(+ name+ for name, pod in pods.items()+ if pod.get("serviceAccountName") in writers and pod.get("automountServiceAccountToken", True)+ )+ assert mounting == ["sie-sie-cluster-gateway"]+++def test_nats_authentication_opt_out(tmp_path: Path) -> None:+ docs = nats_documents(tmp_path, {**NATS_L4_POOL, "nats": {"auth": {"enabled": False}}})+ assert nats_auth_secrets(docs) == {}+ assert nats_client_credentials(docs) == {}+ assert not [name for name in workload_env(docs, "sie-nats", "nats") if name.startswith("SIE_NATS")]+ assert "authorization" not in nats_server_config(docs)+++def test_nats_operator_secrets_are_used_unchanged(tmp_path: Path) -> None:+ existing = {"config": "ops-config", "gateway": "ops-gateway", "worker": "ops-worker"}+ docs = nats_documents(tmp_path, {**NATS_L4_POOL, "nats": {"auth": {"existingSecrets": existing}}})+ assert nats_auth_secrets(docs) == {}+ assert nats_client_credentials(docs) == {+ component: (f"sie-{component}", {"name": name, "key": "password"}) for component, name in existing.items()+ }+ server_env = workload_env(docs, "sie-nats", "nats")+ for component, name in existing.items():+ assert server_env[f"SIE_NATS_AUTH_{component.upper()}_PASSWORD"]["valueFrom"]["secretKeyRef"]["name"] == name+++def test_nats_cluster_routes_authenticate(tmp_path: Path) -> None:+ docs = nats_documents(tmp_path, {}, "-f", str(ROOT / helm.CHART_DIR / "values-ha.yaml"))+ assert "sie-nats-auth-route" in nats_auth_secrets(docs)+ config = nats_server_config(docs)+ assert '"password": $SIE_NATS_AUTH_ROUTE_PASSWORD' in config+ assert '"routes": $SIE_NATS_ROUTES' in config+ env_names = list(workload_env(docs, "sie-nats", "nats"))+ assert env_names.index("SIE_NATS_AUTH_ROUTE_PASSWORD") < env_names.index("SIE_NATS_ROUTES")+ routes = workload_env(docs, "sie-nats", "nats")["SIE_NATS_ROUTES"]["value"]+ assert routes == (+ "["+ + ",".join(+ f"nats://sie-route:$(SIE_NATS_AUTH_ROUTE_PASSWORD)@sie-nats-{i}.sie-nats-headless:6222" for i in range(3)+ )+ + "]"+ )+++ ("values", "extra"),+ [+ ({"nats": {"config": {"merge": {"sieNatsAuth": None}}}}, ()),+ ({"nats": {"container": {"env": {"sieNatsAuth": None}}}}, ()),+ (+ {"nats": {"config": {"cluster": {"merge": {"sieNatsAuth": None}}}}},+ ("-f", str(ROOT / helm.CHART_DIR / "values-ha.yaml")),+ ),+ ],+)+def test_nats_values_without_the_server_wiring_fail_the_render(+ tmp_path: Path, values: dict, extra: tuple[str, ...]+) -> None:+ result = render_nats_chart(tmp_path, values, *extra)+ assert result.returncode != 0+ assert "lack the chart's server wiring" in result.stderr+ assert "--reset-then-reuse-values" in result.stderr+++def test_external_nats_needs_operator_secrets(tmp_path: Path) -> None:+ external = {"install": False, "url": "nats://external-nats:4222"}+ result = render_nats_chart(tmp_path, {**NATS_L4_POOL, "nats": external})+ assert result.returncode != 0+ assert "needs nats.auth.existingSecrets.gateway" in result.stderr++ existing = {"config": "ops-config", "gateway": "ops-gateway", "worker": "ops-worker"}+ docs = nats_documents(tmp_path, {**NATS_L4_POOL, "nats": {**external, "auth": {"existingSecrets": existing}}})+ assert nats_auth_secrets(docs) == {}+ assert nats_client_credentials(docs) == {+ component: (f"sie-{component}", {"name": name, "key": "password"}) for component, name in existing.items()+ }++ docs = nats_documents(tmp_path, {**NATS_L4_POOL, "nats": {**external, "auth": {"enabled": False}}})+ assert nats_client_credentials(docs) == {}+++def test_nats_anonymous_upgrade_aid(tmp_path: Path) -> None:+ docs = nats_documents(tmp_path, {"nats": {"auth": {"allowAnonymous": True}}})+ config = nats_server_config(docs)+ assert '"no_auth_user": "sie-anonymous"' in config+ assert '"user": "sie-anonymous"' in config++ external = {"install": False, "url": "nats://external-nats:4222", "auth": {"allowAnonymous": True}}+ result = render_nats_chart(tmp_path, {"nats": external})+ assert result.returncode != 0+ assert "allowAnonymous applies only to the bundled NATS server" in result.stderr+++ ("password", "error"),+ [+ ("", "Secret nats exists but has no password key"),+ ("a" * 31, "shorter than 32 characters"),+ ("a" * 31 + "$", "not letters and digits starting with a letter"),+ ("1" + "a" * 31, "not letters and digits starting with a letter"),+ ("a" * 32, None),+ ],+)+def test_reused_nats_password_must_be_32_letters_and_digits(tmp_path: Path, password: str, error: str | None) -> None:+ chart = tmp_path / "helper-check"+ (chart / "templates").mkdir(parents=True)+ (chart / "Chart.yaml").write_text("apiVersion: v2\nname: helper-check\nversion: 0.1.0\n", encoding="utf-8")+ shutil.copy(ROOT / helm.CHART_DIR / "templates" / "_nats-auth.tpl", chart / "templates" / "_nats-auth.tpl")+ data = base64.b64encode(password.encode()).decode()+ (chart / "templates" / "check.yaml").write_text(+ f'{{{{- include "sie-cluster.nats.validateReusedPassword" (dict "name" "nats" "data" "{data}") }}}}\n',+ encoding="utf-8",+ )+ result = subprocess.run(+ ["mise", "exec", "--", "helm", "template", "check", str(chart)],+ cwd=ROOT,+ capture_output=True,+ text=True,+ check=False,+ )+ if error is None:+ assert result.returncode == 0, result.stderr+ else:+ assert result.returncode != 0+ assert error in result.stderr+++def _free_port() -> int:+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]+++def _route_count(monitor_port: int) -> int:+ with urllib.request.urlopen(f"http://127.0.0.1:{monitor_port}/routez", timeout=2) as response:+ return len({route["remote_id"] for route in json.load(response).get("routes") or []})+++def test_rendered_nats_cluster_forms_only_with_route_credentials(tmp_path: Path) -> None:+ binary = shutil.which("nats-server")+ if binary is None:+ pytest.skip("nats-server is not on PATH")+ docs = nats_documents(tmp_path, {}, "-f", str(ROOT / helm.CHART_DIR / "values-ha.yaml"))+ rendered = nats_server_config(docs)+ assert rendered.count('"store_dir": "/data"') == 1+ assert rendered.count('"port": 6222') == 1+ route_password = "RoutePassword0123456789abcdefghijk"+ cluster_ports = [_free_port() for _ in range(3)]+ monitor_ports = [_free_port() for _ in range(3)]+ routes = ",".join(f"nats://sie-route:{route_password}@127.0.0.1:{port}" for port in cluster_ports)+ servers = []++ def start(index: int, *args: str, env: dict[str, str]) -> subprocess.Popen[bytes]:+ work = tmp_path / f"node-{index}"+ work.mkdir()+ if env:+ config = work / "nats.conf"+ node_config = rendered.replace('"store_dir": "/data"', f'"store_dir": {json.dumps(str(work / "js"))}')+ node_config = node_config.replace('"port": 6222', f'"port": {cluster_ports[index]}')+ config.write_text(node_config, encoding="utf-8")+ args = ("-c", str(config), *args)+ else:+ args = ("-sd", str(work / "js"), *args)+ server = subprocess.Popen( # noqa: S603+ [binary, *args, "-a", "127.0.0.1", "-p", str(_free_port()), "-P", str(work / "pid")],+ env={**os.environ, **env},+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ servers.append(server)+ return server++ try:+ for index in range(3):+ start(+ index,+ "-m",+ str(monitor_ports[index]),+ env={+ "SERVER_NAME": f"node-{index}",+ "SIE_NATS_AUTH_CONFIG_PASSWORD": "c" * 32,+ "SIE_NATS_AUTH_GATEWAY_PASSWORD": "g" * 32,+ "SIE_NATS_AUTH_WORKER_PASSWORD": "w" * 32,+ "SIE_NATS_AUTH_ROUTE_PASSWORD": route_password,+ "SIE_NATS_ROUTES": f"[{routes}]",+ },+ )+ deadline = time.monotonic() + 20+ while True:+ try:+ if all(_route_count(port) == 2 for port in monitor_ports):+ break+ except OSError:+ pass+ assert time.monotonic() < deadline, "the three rendered nodes did not route to each other"+ time.sleep(0.2)++ start(+ 3,+ "--cluster_name",+ "sie-nats",+ "-cluster",+ f"nats://127.0.0.1:{_free_port()}",+ "-routes",+ f"nats://127.0.0.1:{cluster_ports[0]}",+ env={},+ )+ time.sleep(3)+ assert _route_count(monitor_ports[0]) == 2, "a route without credentials joined the cluster"+ finally:+ for server in servers:+ server.terminate()+ for server in servers:+ server.wait(timeout=10)diff --git a/tools/ci/tests/test_nats_auth.py b/tools/ci/tests/test_nats_auth.pynew file mode 100644index 000000000..182291499--- /dev/null+++ b/tools/ci/tests/test_nats_auth.py@@ -0,0 +1,333 @@+"""The NATS users and permissions of the chart, on a real nats-server.++The server runs the configuration the chart renders by default+(tools/ci/fixtures/sie-cluster-nats.conf, which test_helm_render.py keeps equal+to the chart).+"""++from __future__ import annotations++import asyncio+import json+import os+import shutil+import socket+import subprocess+import time+from collections.abc import Iterator+from pathlib import Path++import nats+import pytest+from nats.aio.client import Client+from sie_config.nats_publisher import NatsPublisher++ROOT = Path(__file__).resolve().parents[3]+SERVER_CONFIG = ROOT / "tools/ci/fixtures/sie-cluster-nats.conf"+PASSWORDS = {+ "config": "ConfigPassword0123456789abcdefghij",+ "gateway": "GatewayPassword0123456789abcdefghi",+ "worker": "WorkerPassword0123456789abcdefghij",+}+WORKER_INBOX_PREFIX = "_INBOX_WORKER"+++def _free_port() -> int:+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]++[email protected](scope="module")+def nats_url(tmp_path_factory: pytest.TempPathFactory) -> Iterator[str]:+ binary = shutil.which("nats-server")+ if binary is None:+ pytest.skip("nats-server is not on PATH")+ work = tmp_path_factory.mktemp("nats")+ port = _free_port()+ env = {+ **os.environ,+ "SERVER_NAME": "sie-auth-matrix",+ **{f"SIE_NATS_AUTH_{name.upper()}_PASSWORD": value for name, value in PASSWORDS.items()},+ }+ server = subprocess.Popen( # noqa: S603+ [+ binary,+ "-c",+ str(SERVER_CONFIG),+ "-a",+ "127.0.0.1",+ "-p",+ str(port),+ "-m",+ str(_free_port()),+ "-sd",+ str(work / "jetstream"),+ "-P",+ str(work / "nats.pid"),+ ],+ env=env,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ try:+ deadline = time.monotonic() + 10+ while True:+ try:+ socket.create_connection(("127.0.0.1", port), timeout=0.2).close()+ break+ except OSError:+ if time.monotonic() > deadline or server.poll() is not None:+ raise RuntimeError("nats-server did not start") from None+ time.sleep(0.05)+ yield f"nats://127.0.0.1:{port}"+ finally:+ server.terminate()+ server.wait(timeout=10)+++class Session:+ """A NATS connection that records the server's asynchronous errors."""++ def __init__(self, client: Client, errors: list[str]) -> None:+ self.client = client+ self.errors = errors++ def violations(self) -> list[str]:+ return [error for error in self.errors if "permissions violation" in error.lower()]+++async def _connect(url: str, component: str) -> Session:+ errors: list[str] = []++ async def record(error: Exception) -> None:+ errors.append(str(error))++ client = await nats.connect(+ url,+ user=f"sie-{component}",+ password=PASSWORDS[component],+ inbox_prefix=WORKER_INBOX_PREFIX if component == "worker" else "_INBOX",+ error_cb=record,+ allow_reconnect=False,+ )+ return Session(client, errors)+++async def _received(subscription: nats.aio.subscription.Subscription) -> list[bytes]:+ messages = []+ while True:+ try:+ message = await subscription.next_msg(timeout=0.5)+ except nats.errors.TimeoutError:+ return messages+ messages.append(message.data)+++async def _api(session: Session, subject: str, body: dict | None = None) -> dict:+ reply = await session.client.request(subject, json.dumps(body or {}).encode(), timeout=2)+ return json.loads(reply.data)+++async def _refused(session: Session, subject: str) -> bool:+ try:+ await session.client.request(subject, b"{}", timeout=1)+ except nats.errors.TimeoutError:+ return True+ return False+++def _run(coroutine):+ return asyncio.run(coroutine)+++ ("user", "password"),+ [(None, None), ("sie-gateway", PASSWORDS["worker"]), ("sie-unknown", PASSWORDS["worker"])],+)+def test_unauthenticated_connections_are_refused(nats_url: str, user: str | None, password: str | None) -> None:+ async def scenario() -> None:+ with pytest.raises(Exception, match=r"(?i)authorization"):+ await nats.connect(nats_url, user=user, password=password, allow_reconnect=False, max_reconnect_attempts=0)++ _run(scenario())+++def test_sie_config_publishes_config_deltas_and_nothing_else(nats_url: str) -> None:+ async def scenario() -> None:+ gateway = await _connect(nats_url, "gateway")+ worker = await _connect(nats_url, "worker")+ config = await _connect(nats_url, "config")+ at_gateway = await gateway.client.subscribe("sie.config.models._all")+ at_worker = await worker.client.subscribe("sie.config.models.default")+ cancels = await worker.client.subscribe("cancel.>")+ await gateway.client.flush()+ await worker.client.flush()++ await config.client.publish("sie.config.models._all", b"all")+ await config.client.publish("sie.config.models.default", b"bundle")+ await config.client.publish("cancel.router.request", b"")+ await config.client.subscribe("sie.health.>")+ await config.client.flush()++ assert await _received(at_gateway) == [b"all"]+ assert await _received(at_worker) == [b"bundle"]+ assert await _received(cancels) == []+ assert len(config.violations()) == 2, config.errors+ for session in (gateway, worker, config):+ await session.client.close()++ _run(scenario())+++def test_sie_config_client_authenticates_with_its_environment(nats_url: str, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_NATS_USER", "sie-config")+ monkeypatch.setenv("SIE_NATS_PASSWORD", PASSWORDS["config"])++ async def scenario() -> None:+ gateway = await _connect(nats_url, "gateway")+ deltas = await gateway.client.subscribe("sie.config.models._all")+ await gateway.client.flush()+ publisher = NatsPublisher(nats_url=nats_url)+ await publisher.connect()+ assert publisher.connected+ await publisher.publish_config_notification(+ model_id="org/model",+ profiles_added=["default"],+ affected_bundles=["default"],+ bundle_config_hashes={"default": "hash"},+ epoch=3,+ model_config_yaml="name: org/model\n",+ )+ (delta,) = await _received(deltas)+ assert json.loads(delta)["epoch"] == 3+ await publisher.disconnect()+ await gateway.client.close()++ _run(scenario())+++def test_sie_config_client_ignores_url_credentials(nats_url: str, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("SIE_NATS_USER", raising=False)+ monkeypatch.delenv("SIE_NATS_PASSWORD", raising=False)+ monkeypatch.setenv("SIE_NATS_STARTUP_CONNECT_TIMEOUT_SEC", "2")+ monkeypatch.setenv("SIE_NATS_URL", nats_url.replace("nats://", f"nats://sie-config:{PASSWORDS['config']}@"))++ async def scenario() -> None:+ publisher = NatsPublisher()+ await publisher.connect()+ assert not publisher.connected+ await publisher.disconnect()++ _run(scenario())+++def test_gateway_permissions(nats_url: str) -> None:+ async def scenario() -> None:+ gateway = await _connect(nats_url, "gateway")+ worker = await _connect(nats_url, "worker")+ at_worker = await worker.client.subscribe("work_cancel.>")+ await worker.client.flush()++ stream = {+ "name": "WORK_POOL_matrix",+ "subjects": ["sie.work.matrix.*.*.*"],+ "retention": "workqueue",+ "storage": "memory",+ "num_replicas": 1,+ }+ created = await _api(gateway, "$JS.API.STREAM.CREATE.WORK_POOL_matrix", stream)+ assert "error" not in created, created+ info = await _api(gateway, "$JS.API.STREAM.INFO.WORK_POOL_matrix")+ assert info["config"]["name"] == "WORK_POOL_matrix"+ ack = await gateway.client.request("sie.work.matrix.cpu.default.model", b"work", timeout=2)+ assert json.loads(ack.data)["seq"] == 1+ dlq = {"name": "DEAD_LETTERS", "subjects": ["sie.dlq.>"], "storage": "memory", "num_replicas": 1}+ assert "error" not in await _api(gateway, "$JS.API.STREAM.CREATE.DEAD_LETTERS", dlq)+ await gateway.client.publish("work_cancel.router.request", b"")+ await gateway.client.subscribe("sie.health.>")+ await gateway.client.subscribe("$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>")+ await gateway.client.flush()+ assert await _received(at_worker) == [b""]+ assert gateway.violations() == []++ await gateway.client.publish("sie.config.models._all", b"{}")+ await gateway.client.subscribe(f"{WORKER_INBOX_PREFIX}.>")+ await gateway.client.flush()+ assert await _refused(gateway, "$JS.API.STREAM.DELETE.WORK_POOL_matrix")+ assert await _refused(gateway, "$JS.API.STREAM.PURGE.WORK_POOL_matrix")+ assert len(gateway.violations()) >= 2, gateway.errors+ for session in (gateway, worker):+ await session.client.close()++ _run(scenario())+++def test_worker_permissions(nats_url: str) -> None:+ async def scenario() -> None:+ gateway = await _connect(nats_url, "gateway")+ worker = await _connect(nats_url, "worker")+ results = await gateway.client.subscribe("_INBOX.router.>")+ heartbeats = await gateway.client.subscribe("sie.health.>")+ await gateway.client.flush()++ stream = {+ "name": "WORK_WORKER_matrix-0",+ "subjects": ["sie.work.wmatrix.cpu.default.*.matrix-0"],+ "retention": "workqueue",+ "storage": "memory",+ "num_replicas": 1,+ }+ assert "error" not in await _api(worker, "$JS.API.STREAM.CREATE.WORK_WORKER_matrix-0", stream)+ consumer = {+ "stream_name": "WORK_WORKER_matrix-0",+ "config": {+ "durable_name": "gen-matrix-0",+ "filter_subject": "sie.work.wmatrix.cpu.default.*.matrix-0",+ "ack_policy": "explicit",+ },+ "action": "create",+ }+ created = await _api(+ worker,+ "$JS.API.CONSUMER.CREATE.WORK_WORKER_matrix-0.gen-matrix-0.sie.work.wmatrix.cpu.default.*.matrix-0",+ consumer,+ )+ assert "error" not in created, created+ assert "error" not in await _api(worker, "$JS.API.CONSUMER.LIST.WORK_WORKER_matrix-0")+ ack = await gateway.client.request("sie.work.wmatrix.cpu.default.model.matrix-0", b"work", timeout=2)+ assert json.loads(ack.data)["seq"] == 1+ pull_inbox = worker.client.new_inbox()+ pulled = await worker.client.subscribe(pull_inbox)+ await worker.client.publish(+ "$JS.API.CONSUMER.MSG.NEXT.WORK_WORKER_matrix-0.gen-matrix-0", b'{"batch":1}', reply=pull_inbox+ )+ work = await pulled.next_msg(timeout=2)+ assert work.data == b"work"+ assert pull_inbox.startswith(f"{WORKER_INBOX_PREFIX}.")+ await work.ack()+ await worker.client.publish("_INBOX.router.request", b"result")+ await worker.client.publish("sie.health.matrix-0", b"heartbeat")+ for subject in ("cancel.>", "work_cancel.>", "batch_cancel.>", "sie.config.models.default"):+ await worker.client.subscribe(subject)+ await worker.client.flush()+ assert await _received(results) == [b"result"]+ assert await _received(heartbeats) == [b"heartbeat"]+ assert worker.violations() == [], worker.errors++ for subject in ("sie.config.models._all", "sie.work.wmatrix.cpu.default.model.matrix-0", "cancel.r.q"):+ await worker.client.publish(subject, b"forged")+ await worker.client.subscribe("_INBOX.>")+ await worker.client.subscribe("sie.health.>")+ await worker.client.flush()+ assert await _refused(worker, "$JS.API.STREAM.DELETE.WORK_WORKER_matrix-0")+ assert await _refused(worker, "$JS.API.STREAM.PURGE.WORK_WORKER_matrix-0")+ assert await _refused(worker, "$JS.API.STREAM.MSG.GET.WORK_WORKER_matrix-0")+ assert await _refused(worker, "$JS.API.DIRECT.GET.WORK_WORKER_matrix-0")+ assert len(worker.violations()) >= 5, worker.errors+ info = await _api(gateway, "$JS.API.STREAM.INFO.WORK_WORKER_matrix-0")+ assert info["state"]["messages"] == 0+ for session in (gateway, worker):+ await session.client.close()++ _run(scenario())