From 173403f1577d5502ca831c70a2611f709cd19c79 Mon Sep 17 00:00:00 2001 From: Marketen Date: Tue, 24 Nov 2026 17:14:57 +0100 Subject: [PATCH 1/2] feat(enclave): run the PII analyzer inside the enclave A key's PII mode was silently ignored on the enclave gateway: the analyzer lived outside it, so masking was switched off there. Confidential requests to models whose provider can read the prompt went out unmasked. Run Presidio inside the enclave so masking works on confidential requests without prompt text leaving measured code: - nexus-enclave-init is the enclave entrypoint. It reads apps/gateway/enclave/services.yaml (Compose-like), brings up loopback, starts Presidio as uid 1001, starts the gateway once Presidio is healthy, restarts a service that exits (clearing its process group first), reaps orphans, and stops everything in reverse order. The gateway launches nothing itself. A service gets a minimal environment unless it opts in. - Dockerfile.enclave: the runtime image is presidio-analyzer 2.2.362 pinned by digest, with the gateway and the init added. - In Nitro builds the gateway refuses a PRESIDIO_ANALYZER_URL that is not http://127.0.0.1: and reaches the analyzer through a loopback-only transport, so the provider-only egress allowlist is unchanged. Requests that require attested inference still skip masking: their provider cannot read the prompt. Ordinary (non-Nitro) builds are unchanged. Co-Authored-By: Claude Fable 5.2 --- README.md | 14 +- apps/gateway/Dockerfile.enclave | 37 +- apps/gateway/cmd/nexus-enclave-init/main.go | 379 ++++++++++++++++++ .../cmd/nexus-enclave-init/main_test.go | 92 +++++ .../cmd/nexus-enclave-init/reaper_linux.go | 63 +++ .../cmd/nexus-enclave-init/reaper_other.go | 6 + apps/gateway/enclave/services.yaml | 24 ++ .../internal/adapters/pii/presidio/adapter.go | 6 +- .../internal/enclave/network/loopback.go | 44 ++ .../internal/enclave/network/loopback_test.go | 51 +++ .../enclave/network/network_default.go | 4 + .../internal/enclave/network/network_nitro.go | 6 + apps/gateway/main.go | 16 +- go.mod | 2 +- 14 files changed, 729 insertions(+), 15 deletions(-) create mode 100644 apps/gateway/cmd/nexus-enclave-init/main.go create mode 100644 apps/gateway/cmd/nexus-enclave-init/main_test.go create mode 100644 apps/gateway/cmd/nexus-enclave-init/reaper_linux.go create mode 100644 apps/gateway/cmd/nexus-enclave-init/reaper_other.go create mode 100644 apps/gateway/enclave/services.yaml create mode 100644 apps/gateway/internal/enclave/network/loopback.go create mode 100644 apps/gateway/internal/enclave/network/loopback_test.go diff --git a/README.md b/README.md index 228c865..127e982 100644 --- a/README.md +++ b/README.md @@ -145,13 +145,23 @@ shared across its API keys; excess requests return 429 with Live entries are never evicted to admit new requests. Metrics bind to loopback in Nitro builds and retain their internal-network listener in ordinary builds. +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:`, 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. + 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 (masking sends the -prompt to the analyzer, and the provider can't read it anyway), and never falls +the Router, 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`): `TINFOIL_CONFIG_REPO` is operator configuration outside the measurements, so diff --git a/apps/gateway/Dockerfile.enclave b/apps/gateway/Dockerfile.enclave index 89710b0..bd5f320 100644 --- a/apps/gateway/Dockerfile.enclave +++ b/apps/gateway/Dockerfile.enclave @@ -1,6 +1,16 @@ # syntax=docker/dockerfile:1.7@sha256:a57df69d0ea827fb7266491f2813635de6f17269be881f696fbfdf2d83dda33e -# Pin upstream build inputs by digest. Together with SOURCE_DATE_EPOCH and +# 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 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. +# +# Pin every upstream input by digest. Together with SOURCE_DATE_EPOCH and # rewrite-timestamp (see deploy/nitro/build-release-assets.sh) this builds # reproducibly: the same revision yields the same PCR0/PCR1/PCR2 on any x86_64 # machine, so a published release can be independently rebuilt and checked with @@ -12,6 +22,9 @@ FROM golang:1.26.11-alpine3.24@sha256:ae52b5bc6ed045a9ed26ab03dc19327a802a9cc9aa ARG SOURCE_REVISION ARG AWS_REGION ARG KMS_KEY_ARN +# Empty builds the non-enclave variant, for running the image locally with +# plain Docker (no vsock, no KMS bootstrap). Releases always use the default. +ARG GO_TAGS=nitro_enclave WORKDIR /src @@ -20,7 +33,6 @@ RUN go mod download COPY . . -# Reject values that could break linker-flag tokenization. RUN printf '%s' "$SOURCE_REVISION" | grep -Eq '^[0-9a-f]{40}$' RUN printf '%s' "$AWS_REGION" | grep -Eq '^[a-z]{2}(-gov)?-[a-z]+-[0-9]+$' RUN printf '%s' "$KMS_KEY_ARN" | grep -Eq '^arn:(aws|aws-us-gov|aws-cn):kms:[a-z0-9-]+:[0-9]{12}:key/[0-9a-fA-F-]{36}$' @@ -28,18 +40,25 @@ RUN printf '%s' "$KMS_KEY_ARN" | grep -Eq '^arn:(aws|aws-us-gov|aws-cn):kms:[a-z RUN CGO_ENABLED=0 GOOS=linux go build \ -buildvcs=false \ -trimpath \ - -tags nitro_enclave \ + -tags "$GO_TAGS" \ -ldflags="-s -w -buildid= \ -X github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/profile.SourceRevision=${SOURCE_REVISION} \ -X github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/profile.AWSRegion=${AWS_REGION} \ -X github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/profile.KMSKeyARN=${KMS_KEY_ARN}" \ - -o /out/gateway ./apps/gateway + -o /out/gateway ./apps/gateway \ + && CGO_ENABLED=0 GOOS=linux go build \ + -buildvcs=false \ + -trimpath \ + -tags "$GO_TAGS" \ + -ldflags="-s -w -buildid=" \ + -o /out/nexus-enclave-init ./apps/gateway/cmd/nexus-enclave-init -# No shell, package manager, or writable application data is included in the -# enclave runtime image. The Go binary is fully static. -FROM scratch +FROM mcr.microsoft.com/presidio-analyzer:2.2.362@sha256:286e3fa7f3a7426e775e8564fe1870f1ba8f999d3ab8bbb8cc46a44355d9d6e9 -COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt +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 -ENTRYPOINT ["/gateway"] +ENTRYPOINT ["/nexus-enclave-init", "-config", "/etc/nexus/enclave-services.yaml"] +CMD [] diff --git a/apps/gateway/cmd/nexus-enclave-init/main.go b/apps/gateway/cmd/nexus-enclave-init/main.go new file mode 100644 index 0000000..7ddcf56 --- /dev/null +++ b/apps/gateway/cmd/nexus-enclave-init/main.go @@ -0,0 +1,379 @@ +// Command nexus-enclave-init starts and supervises the processes that share +// one Nitro enclave, from a Compose-like file baked into the measured image: +// +// services: +// presidio: +// command: ["gunicorn", "-b", "127.0.0.1:3000", "app:create_app()"] +// workdir: /app +// user: 1001 +// inherit_env: true +// health: {url: "http://127.0.0.1:3000/health", timeout_seconds: 120} +// gateway: +// command: ["/gateway"] +// depends_on: [presidio] +// +// It brings up loopback, starts services in dependency order (each one only +// after the services it depends on answer their health check), restarts a +// 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. +package main + +import ( + "bufio" + "bytes" + "context" + "errors" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "os/exec" + "os/signal" + "sort" + "sync" + "syscall" + "time" + + enclavenetwork "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/network" + "go.yaml.in/yaml/v3" +) + +// managedPIDs holds the processes the init started; their supervisors +// collect them, and the reaper leaves them alone. startMu makes "start a +// process and record its pid" one step as far as the reaper can tell, so a +// service that dies immediately is never mistaken for an orphan. +var ( + managedPIDs sync.Map + startMu sync.RWMutex +) + +type spec struct { + Services map[string]*service `yaml:"services"` +} + +type service struct { + Command []string `yaml:"command"` + Workdir string `yaml:"workdir"` + User *uint32 `yaml:"user"` // Numeric uid/gid; unset runs as the init's user. + Env map[string]string `yaml:"env"` + // 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). + InheritEnv bool `yaml:"inherit_env"` + DependsOn []string `yaml:"depends_on"` + Restart string `yaml:"restart"` // always (default) | no + Health *health `yaml:"health"` + + name string + mu sync.Mutex + cmd *exec.Cmd + running bool +} + +type health struct { + URL string `yaml:"url"` + TimeoutSeconds int `yaml:"timeout_seconds"` +} + +func main() { + log.SetFlags(log.LstdFlags | log.LUTC) + log.SetPrefix("[init] ") + path := flag.String("config", "/etc/nexus/enclave-services.yaml", "services file") + flag.Parse() + + s, order, err := load(*path) + if err != nil { + log.Fatalf("invalid services file: %v", err) + } + if err := enclavenetwork.ConfigureLoopback(); err != nil { + log.Fatalf("configure loopback: %v", err) + } + startReaper(func(pid int) bool { + startMu.RLock() + defer startMu.RUnlock() + _, ok := managedPIDs.Load(pid) + return ok + }) + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) + defer stop() + + var wg sync.WaitGroup + for _, name := range order { + svc := s.Services[name] + started := make(chan error, 1) + wg.Add(1) + go func() { + defer wg.Done() + supervise(ctx, svc, started) + }() + if err := <-started; err != nil { + log.Printf("%s did not start: %v", name, err) + stop() + shutdown(s, order) + wg.Wait() + os.Exit(1) + } + if svc.Health != nil { + if err := waitHealthy(ctx, svc); err != nil { + log.Printf("%s never became healthy: %v", name, err) + stop() + shutdown(s, order) + wg.Wait() + os.Exit(1) + } + } + log.Printf("%s is up", name) + } + + <-ctx.Done() + log.Printf("stopping services") + shutdown(s, order) + wg.Wait() +} + +// load reads the services file and returns a start order in which every +// service comes after its dependencies; ties sort by name. +func load(path string) (*spec, []string, error) { + raw, err := os.ReadFile(path) + if err != nil { + return nil, nil, err + } + var s spec + dec := yaml.NewDecoder(bytes.NewReader(raw)) + dec.KnownFields(true) + if err := dec.Decode(&s); err != nil { + return nil, nil, err + } + if len(s.Services) == 0 { + return nil, nil, errors.New("no services") + } + for name, svc := range s.Services { + svc.name = name + if len(svc.Command) == 0 { + return nil, nil, fmt.Errorf("%s: command is required", name) + } + if svc.Restart != "" && svc.Restart != "always" && svc.Restart != "no" { + return nil, nil, fmt.Errorf("%s: restart must be always or no", name) + } + for _, dep := range svc.DependsOn { + if _, ok := s.Services[dep]; !ok { + return nil, nil, fmt.Errorf("%s depends on unknown service %s", name, dep) + } + } + } + order, err := startOrder(s.Services) + return &s, order, err +} + +func startOrder(services map[string]*service) ([]string, error) { + names := make([]string, 0, len(services)) + for name := range services { + names = append(names, name) + } + sort.Strings(names) + state := map[string]int{} // 1 visiting, 2 done + var order []string + var visit func(string) error + visit = func(name string) error { + switch state[name] { + case 1: + return fmt.Errorf("dependency cycle through %s", name) + case 2: + return nil + } + state[name] = 1 + deps := append([]string(nil), services[name].DependsOn...) + sort.Strings(deps) + for _, dep := range deps { + if err := visit(dep); err != nil { + return err + } + } + state[name] = 2 + order = append(order, name) + return nil + } + for _, name := range names { + if err := visit(name); err != nil { + return nil, err + } + } + return order, nil +} + +// supervise runs svc until ctx ends, restarting it with backoff when it +// exits. started receives the result of the first start. +func supervise(ctx context.Context, svc *service, started chan<- error) { + backoff := time.Second + for attempt := 0; ; attempt++ { + cmd, err := start(svc) + if attempt == 0 { + started <- err + } + if err != nil { + if attempt > 0 && ctx.Err() == nil { + log.Printf("%s failed to restart: %v", svc.name, err) + } + return + } + began := time.Now() + err = cmd.Wait() + managedPIDs.Delete(cmd.Process.Pid) + // A service's leftovers (a worker whose parent died) can still hold + // its port, so clear its whole process group before any restart. + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + svc.mu.Lock() + svc.running = false + svc.mu.Unlock() + if ctx.Err() != nil { + return + } + log.Printf("%s exited after %s: %v", svc.name, time.Since(began).Round(time.Millisecond), err) + if svc.Restart == "no" { + return + } + if time.Since(began) > time.Minute { + backoff = time.Second + } + select { + case <-ctx.Done(): + return + case <-time.After(backoff): + } + if backoff < 30*time.Second { + backoff *= 2 + } + log.Printf("restarting %s", svc.name) + } +} + +func start(svc *service) (*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() + } + keys := make([]string, 0, len(svc.Env)) + for k := range svc.Env { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + cmd.Env = append(cmd.Env, k+"="+svc.Env[k]) + } + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if svc.User != nil { + cmd.SysProcAttr.Credential = &syscall.Credential{Uid: *svc.User, Gid: *svc.User} + } + stdout, err := cmd.StdoutPipe() + if err != nil { + return nil, err + } + stderr, err := cmd.StderrPipe() + if err != nil { + return nil, err + } + startMu.Lock() + err = cmd.Start() + if err == nil { + managedPIDs.Store(cmd.Process.Pid, struct{}{}) + } + startMu.Unlock() + if err != nil { + return nil, err + } + go prefix(svc.name, stdout, os.Stdout) + go prefix(svc.name, stderr, os.Stderr) + svc.mu.Lock() + svc.cmd = cmd + svc.running = true + svc.mu.Unlock() + return cmd, 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=/"} + if lang, ok := os.LookupEnv("LANG"); ok { + env = append(env, "LANG="+lang) + } + return env +} + +func prefix(name string, r io.Reader, w io.Writer) { + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 64*1024), 1024*1024) + for sc.Scan() { + fmt.Fprintf(w, "[%s] %s\n", name, sc.Bytes()) + } +} + +func waitHealthy(ctx context.Context, svc *service) error { + timeout := time.Duration(svc.Health.TimeoutSeconds) * time.Second + if timeout <= 0 { + timeout = 60 * time.Second + } + // Health checks only ever go to loopback. + client := &http.Client{Timeout: 2 * time.Second, Transport: enclavenetwork.LoopbackTransport()} + deadline := time.Now().Add(timeout) + began := time.Now() + for time.Now().Before(deadline) { + if ctx.Err() != nil { + return ctx.Err() + } + resp, err := client.Get(svc.Health.URL) + if err == nil { + resp.Body.Close() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + log.Printf("%s healthy after %s", svc.name, time.Since(began).Round(100*time.Millisecond)) + return nil + } + } + time.Sleep(250 * time.Millisecond) + } + return fmt.Errorf("no healthy answer from %s within %s", svc.Health.URL, timeout) +} + +// shutdown sends SIGTERM to each running service, dependents first, and +// SIGKILL to any still running 10 seconds later. +func shutdown(s *spec, order []string) { + for i := len(order) - 1; i >= 0; i-- { + signalGroup(s.Services[order[i]], syscall.SIGTERM) + } + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + if !anyRunning(s) { + return + } + time.Sleep(100 * time.Millisecond) + } + for _, name := range order { + signalGroup(s.Services[name], syscall.SIGKILL) + } +} + +func signalGroup(svc *service, sig syscall.Signal) { + svc.mu.Lock() + defer svc.mu.Unlock() + if svc.running && svc.cmd != nil && svc.cmd.Process != nil { + _ = syscall.Kill(-svc.cmd.Process.Pid, sig) + } +} + +func anyRunning(s *spec) bool { + for _, svc := range s.Services { + svc.mu.Lock() + running := svc.running + svc.mu.Unlock() + if running { + return true + } + } + return false +} diff --git a/apps/gateway/cmd/nexus-enclave-init/main_test.go b/apps/gateway/cmd/nexus-enclave-init/main_test.go new file mode 100644 index 0000000..46df497 --- /dev/null +++ b/apps/gateway/cmd/nexus-enclave-init/main_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "os" + "path/filepath" + "reflect" + "strings" + "testing" +) + +func writeSpec(t *testing.T, body string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "services.yaml") + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func TestStartOrderFollowsDependencies(t *testing.T) { + _, order, err := load(writeSpec(t, ` +services: + gateway: + command: ["/gateway"] + depends_on: [presidio, router] + router: + command: ["/router"] + presidio: + command: ["gunicorn"] +`)) + if err != nil { + t.Fatal(err) + } + if want := []string{"presidio", "router", "gateway"}; !reflect.DeepEqual(order, want) { + t.Fatalf("order = %v, want %v", order, want) + } +} + +func TestShippedServicesFile(t *testing.T) { + s, order, err := load(filepath.Join("..", "..", "enclave", "services.yaml")) + if err != nil { + t.Fatalf("the services file baked into the image does not load: %v", err) + } + if order[len(order)-1] != "gateway" { + t.Fatalf("the gateway must start last, got %v", order) + } + if s.Services["gateway"].InheritEnv { + t.Fatal("the gateway must not inherit the image environment (Presidio sets PORT)") + } + if url := s.Services["gateway"].Env["PRESIDIO_ANALYZER_URL"]; !strings.HasPrefix(url, "http://127.0.0.1:") { + t.Fatalf("PRESIDIO_ANALYZER_URL = %q, want a loopback URL", url) + } +} + +func TestInvalidSpecsAreRejected(t *testing.T) { + cases := map[string]string{ + "unknown dependency": ` +services: + gateway: {command: ["/gateway"], depends_on: [missing]}`, + "cycle": ` +services: + a: {command: ["/a"], depends_on: [b]} + b: {command: ["/b"], depends_on: [a]}`, + "no command": ` +services: + gateway: {depends_on: []}`, + "bad restart policy": ` +services: + gateway: {command: ["/gateway"], restart: sometimes}`, + "unknown field": ` +services: + gateway: {command: ["/gateway"], restat: always}`, + "no services": `services: {}`, + } + for name, body := range cases { + t.Run(name, func(t *testing.T) { + if _, _, err := load(writeSpec(t, body)); err == nil { + t.Fatal("want an error") + } + }) + } +} + +func TestBaseEnvironmentIsMinimal(t *testing.T) { + t.Setenv("PORT", "3000") + t.Setenv("METERING_TOKEN", "secret") + for _, kv := range baseEnv() { + if strings.HasPrefix(kv, "PORT=") || strings.HasPrefix(kv, "METERING_TOKEN=") { + t.Fatalf("base environment leaks %q", kv) + } + } +} diff --git a/apps/gateway/cmd/nexus-enclave-init/reaper_linux.go b/apps/gateway/cmd/nexus-enclave-init/reaper_linux.go new file mode 100644 index 0000000..5692662 --- /dev/null +++ b/apps/gateway/cmd/nexus-enclave-init/reaper_linux.go @@ -0,0 +1,63 @@ +//go:build linux + +package main + +import ( + "log" + "os" + "os/signal" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/unix" +) + +// startReaper collects processes orphaned onto the init, such as a worker +// whose parent was killed, so they do not stay as zombies. It only reaps +// processes the init did not start itself: those are left for exec.Cmd.Wait, +// which needs their exit status. WNOWAIT peeks at an exited child without +// consuming it, so the two never race. +func startReaper(managed func(pid int) bool) { + // Outside PID 1 (the Nitro init may run us as its child), ask the kernel + // to hand orphans to us anyway. + if os.Getpid() != 1 { + if err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0); err != nil { + log.Printf("cannot become child subreaper: %v", err) + } + } + sigchld := make(chan os.Signal, 16) + signal.Notify(sigchld, syscall.SIGCHLD) + // A sweep every few seconds catches an orphan that exited while a + // managed child was still waiting to be collected. + tick := time.NewTicker(3 * time.Second) + go func() { + for { + select { + case <-sigchld: + case <-tick.C: + } + for { + var info unix.Siginfo + err := unix.Waitid(unix.P_ALL, 0, &info, unix.WEXITED|unix.WNOHANG|unix.WNOWAIT, nil) + pid := siginfoPid(&info) + if err != nil || pid == 0 { + break + } + if managed(pid) { + // Its supervisor collects it. Stop here: Waitid with + // WNOWAIT keeps returning the same child until then. + break + } + var status unix.WaitStatus + _, _ = unix.Wait4(pid, &status, unix.WNOHANG, nil) + } + } + }() +} + +// siginfoPid reads si_pid, which follows si_signo, si_errno, si_code and +// padding at byte 16 of siginfo_t on 64-bit Linux. +func siginfoPid(info *unix.Siginfo) int { + return int(*(*int32)(unsafe.Pointer(uintptr(unsafe.Pointer(info)) + 16))) +} diff --git a/apps/gateway/cmd/nexus-enclave-init/reaper_other.go b/apps/gateway/cmd/nexus-enclave-init/reaper_other.go new file mode 100644 index 0000000..52b07c9 --- /dev/null +++ b/apps/gateway/cmd/nexus-enclave-init/reaper_other.go @@ -0,0 +1,6 @@ +//go:build !linux + +package main + +// startReaper does nothing off Linux; the init only runs in the enclave. +func startReaper(func(pid int) bool) {} diff --git a/apps/gateway/enclave/services.yaml b/apps/gateway/enclave/services.yaml new file mode 100644 index 0000000..337c5c3 --- /dev/null +++ b/apps/gateway/enclave/services.yaml @@ -0,0 +1,24 @@ +# Processes that share the gateway enclave. Read by nexus-enclave-init and +# baked into the measured image, so changing it changes PCR0. +services: + presidio: + # One worker holds about 0.75 GiB (spaCy en_core_web_lg). Each extra + # worker adds the same again and raises throughput roughly linearly. + command: ["gunicorn", "-w", "1", "-b", "127.0.0.1:3000", "app:create_app()"] + workdir: /app + user: 1001 + # Presidio reads its configuration from the image's ENV. + inherit_env: true + health: + url: http://127.0.0.1:3000/health + timeout_seconds: 180 + + gateway: + command: ["/gateway"] + depends_on: [presidio] + # The gateway gets only what is listed here; its secrets and the rest of + # its configuration arrive through the KMS bootstrap, as today. + env: + PORT: "8080" + PII_FILTER_ENABLED: "true" + PRESIDIO_ANALYZER_URL: http://127.0.0.1:3000 diff --git a/apps/gateway/internal/adapters/pii/presidio/adapter.go b/apps/gateway/internal/adapters/pii/presidio/adapter.go index 82720e5..ecc365a 100644 --- a/apps/gateway/internal/adapters/pii/presidio/adapter.go +++ b/apps/gateway/internal/adapters/pii/presidio/adapter.go @@ -31,6 +31,10 @@ type Config struct { Timeout time.Duration // Logger receives debug / warn events. Required. Logger ports.Logger + // Transport carries analyzer calls. Nil uses http.DefaultTransport, which + // the enclave replaces with its provider-only egress, so the enclave passes + // a loopback transport here. + Transport http.RoundTripper } // Adapter implements ports.PIIFilter against Presidio's `/analyze` endpoint. @@ -53,7 +57,7 @@ func NewAdapter(cfg Config) *Adapter { } return &Adapter{ cfg: cfg, - client: &http.Client{Timeout: cfg.Timeout}, + client: &http.Client{Timeout: cfg.Timeout, Transport: cfg.Transport}, } } diff --git a/apps/gateway/internal/enclave/network/loopback.go b/apps/gateway/internal/enclave/network/loopback.go new file mode 100644 index 0000000..f98ef64 --- /dev/null +++ b/apps/gateway/internal/enclave/network/loopback.go @@ -0,0 +1,44 @@ +package network + +import ( + "context" + "fmt" + "net" + "net/http" + "net/netip" + "time" +) + +// LoopbackTransport returns an HTTP transport that only connects to IP +// literals in 127.0.0.0/8. Services that run inside the same enclave (the PII +// analyzer, the router) are reached through it; any other destination fails, +// so a misconfigured URL cannot become a new way out of the enclave. +func LoopbackTransport() *http.Transport { + dialer := &net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second} + return &http.Transport{ + Proxy: nil, + DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { + if err := CheckLoopbackAddress(address); err != nil { + return nil, err + } + return dialer.DialContext(ctx, network, address) + }, + MaxIdleConns: 32, + MaxIdleConnsPerHost: 32, + IdleConnTimeout: 90 * time.Second, + } +} + +// CheckLoopbackAddress accepts host:port where host is an IPv4 loopback +// literal. Names are refused: inside the enclave nothing resolves them. +func CheckLoopbackAddress(address string) error { + host, _, err := net.SplitHostPort(address) + if err != nil { + return fmt.Errorf("in-enclave destination %q is invalid: %w", address, err) + } + ip, err := netip.ParseAddr(host) + if err != nil || !ip.Is4() || !ip.IsLoopback() { + return fmt.Errorf("in-enclave destination %q is not an IPv4 loopback address", address) + } + return nil +} diff --git a/apps/gateway/internal/enclave/network/loopback_test.go b/apps/gateway/internal/enclave/network/loopback_test.go new file mode 100644 index 0000000..e335320 --- /dev/null +++ b/apps/gateway/internal/enclave/network/loopback_test.go @@ -0,0 +1,51 @@ +package network + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestCheckLoopbackAddress(t *testing.T) { + for _, ok := range []string{"127.0.0.1:3000", "127.0.0.2:8083"} { + if err := CheckLoopbackAddress(ok); err != nil { + t.Errorf("%s refused: %v", ok, err) + } + } + for _, bad := range []string{ + "localhost:3000", // names never resolve inside the enclave + "presidio-analyzer:3000", // the regular stack's analyzer + "10.200.200.31:3000", // another host + "[::1]:3000", // IPv6 loopback is not configured + "127.0.0.1", // no port + "api.deepseek.com:443", // a provider + } { + if err := CheckLoopbackAddress(bad); err == nil { + t.Errorf("%s accepted", bad) + } + } +} + +func TestLoopbackTransportReachesLoopbackServices(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusNoContent) + })) + defer server.Close() + client := &http.Client{Transport: LoopbackTransport()} + resp, err := client.Get(server.URL) + if err != nil { + t.Fatalf("loopback service unreachable: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusNoContent { + t.Fatalf("status = %d", resp.StatusCode) + } +} + +func TestLoopbackTransportRefusesOtherHosts(t *testing.T) { + dial := LoopbackTransport().DialContext + if _, err := dial(context.Background(), "tcp", "93.184.216.34:443"); err == nil { + t.Fatal("dialed a public address") + } +} diff --git a/apps/gateway/internal/enclave/network/network_default.go b/apps/gateway/internal/enclave/network/network_default.go index f75bc3b..b6c8f3b 100644 --- a/apps/gateway/internal/enclave/network/network_default.go +++ b/apps/gateway/internal/enclave/network/network_default.go @@ -21,3 +21,7 @@ func ConfigureRouterTransport(*http.Transport) {} func ConfigureDefaultTransport() error { return nil } func StartTinfoilTLSBridge() (net.Listener, error) { return nil, nil } + +// ConfigureLoopback is a no-op outside the enclave, where the OS already +// brings up loopback. +func ConfigureLoopback() error { return nil } diff --git a/apps/gateway/internal/enclave/network/network_nitro.go b/apps/gateway/internal/enclave/network/network_nitro.go index c7e5f22..2b28c52 100644 --- a/apps/gateway/internal/enclave/network/network_nitro.go +++ b/apps/gateway/internal/enclave/network/network_nitro.go @@ -77,6 +77,12 @@ func StartTinfoilTLSBridge() (net.Listener, error) { return listener, nil } +// ConfigureLoopback brings up 127.0.0.1 on lo. The enclave init calls it +// before starting in-enclave services; calling it again is harmless. +func ConfigureLoopback() error { + return configureIPv4Loopback() +} + func configureIPv4Loopback() error { fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM|unix.SOCK_CLOEXEC, 0) if err != nil { diff --git a/apps/gateway/main.go b/apps/gateway/main.go index 719cee6..da962f1 100644 --- a/apps/gateway/main.go +++ b/apps/gateway/main.go @@ -6,6 +6,7 @@ import ( "fmt" "log" "net/http" + neturl "net/url" "os" "os/signal" "strconv" @@ -254,13 +255,24 @@ func buildPIIFilter(log *logger.ZapLogger) (ports.PIIFilter, string, bool) { "timeout_ms", timeout.Milliseconds(), "fail_open", failOpen, ) - return presidio.NewAdapter(presidio.Config{ + cfg := presidio.Config{ BaseURL: url, DefaultLanguage: language, ScoreThreshold: threshold, Timeout: timeout, Logger: log, - }), language, failOpen + } + if profile.Enabled { + // Inside the enclave the analyzer runs as a sibling process. Refuse + // any URL that would send prompt text anywhere but loopback. + parsed, err := neturl.Parse(url) + if err != nil || parsed.Scheme != "http" || enclavenetwork.CheckLoopbackAddress(parsed.Host) != nil { + log.Error("PRESIDIO_ANALYZER_URL must be http://127.0.0.1: inside the enclave", "analyzer_url", url) + os.Exit(1) + } + cfg.Transport = enclavenetwork.LoopbackTransport() + } + return presidio.NewAdapter(cfg), language, failOpen } // positiveIntEnv reads a positive whole number from the environment. A set but diff --git a/go.mod b/go.mod index 6e1455b..aebcebd 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/tinfoilsh/encrypted-http-body-protocol v0.2.6 github.com/tinfoilsh/tinfoil-go v0.13.1 go.uber.org/zap v1.28.0 + go.yaml.in/yaml/v3 v3.0.4 golang.org/x/image v0.48.0 golang.org/x/net v0.60.0 golang.org/x/sync v0.25.0 @@ -110,7 +111,6 @@ require ( go.opentelemetry.io/otel/trace v1.44.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/crypto v0.57.0 // indirect golang.org/x/mod v0.42.0 // indirect golang.org/x/term v0.46.0 // indirect From 65e5ed5c6a2a4f46dbf96369da287cc35518a1f9 Mon Sep 17 00:00:00 2001 From: Marketen Date: Tue, 24 Nov 2026 17:25:33 +0100 Subject: [PATCH 2/2] refactor(enclave): use Compose key names in the enclave services file working_dir and environment mean what they mean in Docker Compose, so the file reads like one. Co-Authored-By: Claude Fable 5.2 --- apps/gateway/cmd/nexus-enclave-init/main.go | 11 +++++++---- apps/gateway/enclave/services.yaml | 10 ++++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/apps/gateway/cmd/nexus-enclave-init/main.go b/apps/gateway/cmd/nexus-enclave-init/main.go index 7ddcf56..22763bd 100644 --- a/apps/gateway/cmd/nexus-enclave-init/main.go +++ b/apps/gateway/cmd/nexus-enclave-init/main.go @@ -1,10 +1,13 @@ // Command nexus-enclave-init starts and supervises the processes that share -// one Nitro enclave, from a Compose-like file baked into the measured image: +// 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): // // services: // presidio: // command: ["gunicorn", "-b", "127.0.0.1:3000", "app:create_app()"] -// workdir: /app +// working_dir: /app // user: 1001 // inherit_env: true // health: {url: "http://127.0.0.1:3000/health", timeout_seconds: 120} @@ -56,9 +59,9 @@ type spec struct { type service struct { Command []string `yaml:"command"` - Workdir string `yaml:"workdir"` + Workdir string `yaml:"working_dir"` User *uint32 `yaml:"user"` // Numeric uid/gid; unset runs as the init's user. - Env map[string]string `yaml:"env"` + Env map[string]string `yaml:"environment"` // 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). diff --git a/apps/gateway/enclave/services.yaml b/apps/gateway/enclave/services.yaml index 337c5c3..1a2cf14 100644 --- a/apps/gateway/enclave/services.yaml +++ b/apps/gateway/enclave/services.yaml @@ -1,11 +1,13 @@ -# Processes that share the gateway enclave. Read by nexus-enclave-init and -# baked into the measured image, so changing it changes PCR0. +# Processes that share the gateway enclave, in Docker Compose's vocabulary. +# A Nitro enclave cannot run Docker, so nexus-enclave-init reads this file and +# does Compose's job. The file is baked into the measured image, so changing it +# changes PCR0. Keys that are not Compose's: health, inherit_env. services: presidio: # One worker holds about 0.75 GiB (spaCy en_core_web_lg). Each extra # worker adds the same again and raises throughput roughly linearly. command: ["gunicorn", "-w", "1", "-b", "127.0.0.1:3000", "app:create_app()"] - workdir: /app + working_dir: /app user: 1001 # Presidio reads its configuration from the image's ENV. inherit_env: true @@ -18,7 +20,7 @@ services: depends_on: [presidio] # The gateway gets only what is listed here; its secrets and the rest of # its configuration arrive through the KMS bootstrap, as today. - env: + environment: PORT: "8080" PII_FILTER_ENABLED: "true" PRESIDIO_ANALYZER_URL: http://127.0.0.1:3000