Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 33 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,22 +147,44 @@ metrics on vsock port 9090, which the parent forwards to Prometheus; ordinary
builds listen on `METRICS_PORT`. Metrics carry model, provider and error labels,
never request content.

The Nitro enclave runs three processes from one measured image:
`nexus-enclave-init` (the entrypoint), the Presidio PII analyzer and the
Gateway. The init reads `apps/gateway/enclave/services.yaml`, starts Presidio as
an unprivileged user, starts the Gateway once Presidio is healthy, restarts
either if it exits, and stops both on shutdown. The Gateway reaches Presidio on
loopback only: a Nitro build refuses to start if `PRESIDIO_ANALYZER_URL` is not
`http://127.0.0.1:<port>`, so prompt text is never sent out of the enclave for
masking. A key's PII mode therefore applies to confidential requests the same
way it does on an ordinary Gateway.
The Nitro enclave runs four processes from one measured image:
`nexus-enclave-init` (the entrypoint), the Presidio PII analyzer, the Gateway
and the Router. The init reads `apps/gateway/enclave/services.yaml`, starts
Presidio as an unprivileged user, starts the Gateway once Presidio is healthy,
then the Router as another unprivileged user, restarts any of them that exits,
and stops them in reverse order on shutdown. The Gateway reaches Presidio and
the Router on loopback only: a Nitro build refuses to start if
`PRESIDIO_ANALYZER_URL` or `ROUTER_URL` is not `http://127.0.0.1:<port>`, so
prompt text is never sent out of the enclave for masking or routing. A key's
PII mode and routers such as `nexus/auto` therefore work on confidential
requests the same way they do on an ordinary Gateway.

The Router is `dappnode-nexus-router` built from the commit pinned in
`apps/gateway/Dockerfile.enclave` (the release the regular Router runs), with
ONNX Runtime and its embedding model pinned by checksum. It has no network of
its own. Two relays in the Gateway give it the same reach as a regular Router,
and nothing more:

- Postgres, for routing configuration, through `127.0.0.1:5432`, which the
Gateway relays to the parent on vsock port 8455. Queries carry router and
model IDs, never prompt text.
- TypeSafe, which the Jev strategy asks to classify a request, through an HTTP
CONNECT proxy on `127.0.0.1:3128` that opens tunnels to `api.typesafe.ai:443`
only, over the same measured route the Gateway's TypeSafe provider uses. TLS
ends at TypeSafe; the parent sees ciphertext.

Its database URL (`ROUTER_DATABASE_URL`, which must point at the relay) and
`TYPESAFE_API_KEY` arrive in the KMS-sealed secret bundle with the Gateway's
own. The Gateway writes them to `/run/nexus/router.env` (enclave RAM, root
only), and the init starts the Router with that file once it exists. The
Router's admin API stays off inside the enclave.

A confidential request may set `"require_attested_inference": true` in its
encrypted envelope, next to `schema_version`, `request_id`, `issued_at` and
`request`. The enclave then lets only attested code read the prompt: itself
and a provider whose attestation it verifies before sending anything (today,
Tinfoil). It refuses routers such as `nexus/auto`, which send the prompt to
the Router, skips PII masking whatever the key's PII mode (the attested
Tinfoil). It refuses routers such as `nexus/auto`, whose Jev strategy sends
the prompt to TypeSafe, skips PII masking whatever the key's PII mode (the attested
provider can't read the prompt anyway), and never falls
back to a provider without that verification. The code the Tinfoil enclave
must run is pinned in this binary (`tinfoilsh/confidential-model-router`):
Expand Down
69 changes: 62 additions & 7 deletions apps/gateway/Dockerfile.enclave
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
# syntax=docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e

# The Nitro enclave image: the gateway, nexus-enclave-init and the Presidio PII
# analyzer, so every request a regular gateway can serve is served inside the
# enclave and prompt text never leaves it for masking.
# The Nitro enclave image: the gateway, nexus-enclave-init, the Presidio PII
# analyzer and the Router, so every request a regular gateway can serve is
# served inside the enclave and prompt text never leaves it for masking or
# routing.
#
# The runtime image is Microsoft's Presidio analyzer pinned by its multi-arch
# index digest, with the two Go binaries added on top. nexus-enclave-init is
# the entrypoint: it starts Presidio as uid 1001 and then the gateway as root
# (the gateway configures the enclave's network), from
# apps/gateway/enclave/services.yaml.
# index digest, with the Go binaries and the Router's model added on top.
# nexus-enclave-init is the entrypoint: it starts Presidio as uid 1001, then
# the gateway as root (the gateway configures the enclave's network), then the
# Router as uid 1002, from apps/gateway/enclave/services.yaml.
#
# Pin every upstream input by digest. Together with SOURCE_DATE_EPOCH and
# rewrite-timestamp (see deploy/nitro/build-release-assets.sh) this builds
Expand Down Expand Up @@ -58,12 +59,66 @@ RUN CGO_ENABLED=0 GOOS=linux go build \
-ldflags="-s -w -buildid=" \
-o /out/nexus-enclave-init ./apps/gateway/cmd/nexus-enclave-init

# The Router's source at the commit the regular Router runs (v0.1.53). BuildKit
# checks out exactly this commit. To build from a local checkout instead, pass
# --build-context router-src=<path to dappnode-nexus-router>; a release must
# use the pinned commit, or its measurements will not reproduce.
FROM scratch AS router-src
ADD https://github.com/dappnode/dappnode-nexus-router.git#816ad35e3fc01bfd9ba061704d282d5fdd322284 /

# The Router links against glibc (ONNX Runtime is a glibc library), so it is
# built on the same Debian release as the Presidio runtime image (trixie).
FROM golang:1.26.11-trixie@sha256:f9e99477a80ccd7adfb69780510b22c7249ce9169885f18aa762cd886e75e018 AS router-builder

ARG TARGETARCH

# ONNX Runtime 1.25.0, the version the Router's onnxruntime_go v1.30.1 expects,
# from Microsoft's NuGet package. The package carries the Linux libraries for
# both architectures; this checksum equals the SHA-512 NuGet publishes for it.
ADD --checksum=sha256:c12a4e043c7ae1cee4ef99a347193eceabe2f6c828eb04f6d58ab21bcccddd8d \
https://api.nuget.org/v3-flatcontainer/microsoft.ml.onnxruntime/1.25.0/microsoft.ml.onnxruntime.1.25.0.nupkg \
/tmp/onnxruntime.nupkg
RUN case "$TARGETARCH" in \
amd64) ort_arch=linux-x64 ;; \
arm64) ort_arch=linux-arm64 ;; \
*) echo "unsupported architecture: $TARGETARCH" >&2; exit 1 ;; \
esac \
&& mkdir -p /out/lib \
&& python3 -c 'import pathlib, sys, zipfile; z = zipfile.ZipFile("/tmp/onnxruntime.nupkg"); out = pathlib.Path("/out/lib"); [(out / dst).write_bytes(z.read(src)) for src, dst in ((f"runtimes/{sys.argv[1]}/native/libonnxruntime.so", "libonnxruntime.so"), ("LICENSE", "ONNXRUNTIME-LICENSE"), ("ThirdPartyNotices.txt", "ONNXRUNTIME-THIRD-PARTY-NOTICES"))]' "$ort_arch" \
&& chmod 0755 /out/lib && chmod 0644 /out/lib/*

WORKDIR /src
COPY --from=router-src / ./
RUN go mod download
RUN CGO_ENABLED=1 GOOS=linux go build \
-buildvcs=false \
-trimpath \
-ldflags="-s -w -buildid=" \
-o /out/router ./apps/router

# The embedding model the Router's embedding strategy uses, pinned to a
# Hugging Face revision and checksum. It must be the model that computed the
# example embeddings stored in the database, the one the regular Router mounts.
FROM scratch AS router-model
ADD --chmod=0644 --checksum=sha256:10f7a088420252b26caf819236ca2c9d2987afd0fc06fec7553b542a5655a05a \
https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/resolve/e8f8c211226b894fcb81acc59f3b34ba3efd5f42/onnx/model.onnx \
/model.onnx
ADD --chmod=0644 --checksum=sha256:2c3387be76557bd40970cec13153b3bbf80407865484b209e655e5e4729076b8 \
https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2/resolve/e8f8c211226b894fcb81acc59f3b34ba3efd5f42/tokenizer.json \
/tokenizer.json

FROM mcr.microsoft.com/presidio-analyzer:2.2.362@sha256:286e3fa7f3a7426e775e8564fe1870f1ba8f999d3ab8bbb8cc46a44355d9d6e9

USER root
COPY --from=builder /out/gateway /gateway
COPY --from=builder /out/nexus-enclave-init /nexus-enclave-init
COPY apps/gateway/enclave/services.yaml /etc/nexus/enclave-services.yaml
COPY --from=router-builder --chmod=0755 /out/router /opt/nexus-router/router
# Modes are set in router-builder: COPY --chmod would also apply to the new
# lib directory and make it unreadable for the Router's user.
COPY --from=router-builder /out/lib/ /opt/nexus-router/lib/
COPY --from=router-src --chmod=0644 /LICENSE /opt/nexus-router/LICENSE
COPY --from=router-model /model.onnx /tokenizer.json /opt/nexus-router/models/

ENTRYPOINT ["/nexus-enclave-init", "-config", "/etc/nexus/enclave-services.yaml"]
CMD []
107 changes: 104 additions & 3 deletions apps/gateway/cmd/nexus-enclave-init/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
// one Nitro enclave. A Nitro enclave has no container runtime, so Docker
// Compose cannot run in it; this plays that role, from a file baked into the
// measured image that uses Compose's own key names where the meaning is the
// same (command, user, working_dir, environment, depends_on, restart):
// same (command, user, working_dir, environment, env_file, depends_on,
// restart):
//
// services:
// presidio:
Expand All @@ -20,6 +21,11 @@
// service that exits, and on SIGTERM stops them in reverse order. If a service
// never becomes healthy the init exits, which ends the enclave visibly instead
// of serving without it.
//
// env_file differs from Compose in one way: a file that does not exist yet is
// waited for instead of being an error. The Gateway writes the Router's file
// once the enclave has received its secrets, which can be minutes after boot.
// The file is read again before every restart.
package main

import (
Expand All @@ -30,12 +36,15 @@ import (
"flag"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"sort"
"strings"
"sync"
"syscall"
"time"
Expand All @@ -62,6 +71,9 @@ type service struct {
Workdir string `yaml:"working_dir"`
User *uint32 `yaml:"user"` // Numeric uid/gid; unset runs as the init's user.
Env map[string]string `yaml:"environment"`
// EnvFiles are read before each start; environment wins over them, as in
// Compose.
EnvFiles envFiles `yaml:"env_file"`
// InheritEnv passes the init's whole environment (the image's ENV) to the
// service. Off by default, so one service's settings cannot leak into
// another (Presidio's image sets PORT=3000, which the gateway also reads).
Expand All @@ -76,6 +88,22 @@ type service struct {
running bool
}

// envFiles accepts Compose's two spellings: one path or a list of paths.
type envFiles []string

func (f *envFiles) UnmarshalYAML(node *yaml.Node) error {
if node.Kind == yaml.ScalarNode {
*f = envFiles{node.Value}
return nil
}
var paths []string
if err := node.Decode(&paths); err != nil {
return err
}
*f = paths
return nil
}

type health struct {
URL string `yaml:"url"`
TimeoutSeconds int `yaml:"timeout_seconds"`
Expand Down Expand Up @@ -114,6 +142,9 @@ func main() {
supervise(ctx, svc, started)
}()
if err := <-started; err != nil {
if ctx.Err() != nil {
break // asked to stop while this service was still waiting
}
log.Printf("%s did not start: %v", name, err)
stop()
shutdown(s, order)
Expand Down Expand Up @@ -162,6 +193,11 @@ func load(path string) (*spec, []string, error) {
if svc.Restart != "" && svc.Restart != "always" && svc.Restart != "no" {
return nil, nil, fmt.Errorf("%s: restart must be always or no", name)
}
for _, path := range svc.EnvFiles {
if !filepath.IsAbs(path) {
return nil, nil, fmt.Errorf("%s: env_file %q must be an absolute path", name, path)
}
}
for _, dep := range svc.DependsOn {
if _, ok := s.Services[dep]; !ok {
return nil, nil, fmt.Errorf("%s depends on unknown service %s", name, dep)
Expand Down Expand Up @@ -213,7 +249,16 @@ func startOrder(services map[string]*service) ([]string, error) {
func supervise(ctx context.Context, svc *service, started chan<- error) {
backoff := time.Second
for attempt := 0; ; attempt++ {
cmd, err := start(svc)
fileEnv, err := waitEnvFiles(ctx, svc)
if err != nil {
if attempt == 0 {
started <- err
} else if ctx.Err() == nil {
log.Printf("%s cannot restart: %v", svc.name, err)
}
return
}
cmd, err := start(svc, fileEnv)
if attempt == 0 {
started <- err
}
Expand Down Expand Up @@ -254,14 +299,16 @@ func supervise(ctx context.Context, svc *service, started chan<- error) {
}
}

func start(svc *service) (*exec.Cmd, error) {
func start(svc *service, fileEnv []string) (*exec.Cmd, error) {
cmd := exec.Command(svc.Command[0], svc.Command[1:]...)
cmd.Dir = svc.Workdir
if svc.InheritEnv {
cmd.Env = os.Environ()
} else {
cmd.Env = baseEnv()
}
// Later entries win in exec, so environment overrides env_file.
cmd.Env = append(cmd.Env, fileEnv...)
keys := make([]string, 0, len(svc.Env))
for k := range svc.Env {
keys = append(keys, k)
Expand Down Expand Up @@ -300,6 +347,60 @@ func start(svc *service) (*exec.Cmd, error) {
return cmd, nil
}

// waitEnvFiles reads the service's env files, waiting for any that do not
// exist yet, and returns their KEY=VALUE entries in order.
func waitEnvFiles(ctx context.Context, svc *service) ([]string, error) {
var env []string
for _, path := range svc.EnvFiles {
waitingSince := time.Time{}
for {
entries, err := readEnvFile(path)
if err == nil {
if !waitingSince.IsZero() {
log.Printf("%s: %s appeared after %s", svc.name, path, time.Since(waitingSince).Round(time.Second))
}
env = append(env, entries...)
break
}
if !errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("read env_file %s: %w", path, err)
}
if waitingSince.IsZero() {
waitingSince = time.Now()
log.Printf("%s: waiting for %s", svc.name, path)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(250 * time.Millisecond):
}
}
}
return env, nil
}

// readEnvFile parses KEY=VALUE lines. Blank lines and lines starting with #
// are skipped; values are taken literally, without quote processing.
func readEnvFile(path string) ([]string, error) {
raw, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var env []string
for i, line := range strings.Split(string(raw), "\n") {
line = strings.TrimSuffix(line, "\r")
if strings.TrimSpace(line) == "" || strings.HasPrefix(strings.TrimSpace(line), "#") {
continue
}
key, _, ok := strings.Cut(line, "=")
if !ok || key == "" || strings.TrimSpace(key) != key {
return nil, fmt.Errorf("line %d is not KEY=VALUE", i+1)
}
env = append(env, line)
}
return env, nil
}

// baseEnv is what a service gets when it does not inherit the environment.
func baseEnv() []string {
env := []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/"}
Expand Down
Loading