diff --git a/README.md b/README.md index c34226c..5d2dbfb 100644 --- a/README.md +++ b/README.md @@ -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:`, 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:`, 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`): diff --git a/apps/gateway/Dockerfile.enclave b/apps/gateway/Dockerfile.enclave index c54056f..1c07944 100644 --- a/apps/gateway/Dockerfile.enclave +++ b/apps/gateway/Dockerfile.enclave @@ -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 @@ -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=; 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 [] diff --git a/apps/gateway/cmd/nexus-enclave-init/main.go b/apps/gateway/cmd/nexus-enclave-init/main.go index 22763bd..9e13f1e 100644 --- a/apps/gateway/cmd/nexus-enclave-init/main.go +++ b/apps/gateway/cmd/nexus-enclave-init/main.go @@ -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: @@ -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 ( @@ -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" @@ -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). @@ -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"` @@ -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) @@ -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) @@ -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 } @@ -254,7 +299,7 @@ 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 { @@ -262,6 +307,8 @@ func start(svc *service) (*exec.Cmd, error) { } 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) @@ -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=/"} diff --git a/apps/gateway/cmd/nexus-enclave-init/main_test.go b/apps/gateway/cmd/nexus-enclave-init/main_test.go index 46df497..b61c0da 100644 --- a/apps/gateway/cmd/nexus-enclave-init/main_test.go +++ b/apps/gateway/cmd/nexus-enclave-init/main_test.go @@ -1,11 +1,17 @@ package main import ( + "context" + "errors" "os" "path/filepath" "reflect" "strings" "testing" + "time" + + enclavenetwork "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/network" + "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/routerservice" ) func writeSpec(t *testing.T, body string) string { @@ -41,14 +47,32 @@ func TestShippedServicesFile(t *testing.T) { 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 want := []string{"presidio", "gateway", "router"}; !reflect.DeepEqual(order, want) { + t.Fatalf("start order = %v, want %v", order, want) + } + gateway, router := s.Services["gateway"], s.Services["router"] + if gateway.InheritEnv || router.InheritEnv { + t.Fatal("only Presidio may inherit the image environment (it sets PORT)") + } + for _, key := range []string{"PRESIDIO_ANALYZER_URL", "ROUTER_URL"} { + if url := gateway.Env[key]; !strings.HasPrefix(url, "http://127.0.0.1:") { + t.Fatalf("%s = %q, want a loopback URL", key, url) + } + } + if gateway.Env["ROUTER_URL"] != "http://127.0.0.1:"+router.Env["PORT"] { + t.Fatalf("ROUTER_URL %q does not match the Router's PORT %q", gateway.Env["ROUTER_URL"], router.Env["PORT"]) + } + if router.User == nil || *router.User == 0 { + t.Fatal("the Router must run as an unprivileged user") } - if s.Services["gateway"].InheritEnv { - t.Fatal("the gateway must not inherit the image environment (Presidio sets PORT)") + if !reflect.DeepEqual([]string(router.EnvFiles), []string{routerservice.EnvFile}) { + t.Fatalf("Router env_file = %v, want the file the gateway writes (%s)", router.EnvFiles, routerservice.EnvFile) } - 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) + if router.Env["HTTPS_PROXY"] != "http://"+enclavenetwork.RouterEgressProxyAddress { + t.Fatalf("Router HTTPS_PROXY = %q, want the gateway's egress proxy", router.Env["HTTPS_PROXY"]) + } + if _, ok := router.Env["ROUTER_ADMIN_TOKEN"]; ok { + t.Fatal("the Router's admin API must stay off inside the enclave") } } @@ -90,3 +114,93 @@ func TestBaseEnvironmentIsMinimal(t *testing.T) { } } } + +func TestEnvFileAcceptsComposeSpellings(t *testing.T) { + s, _, err := load(writeSpec(t, ` +services: + one: {command: ["/one"], env_file: /run/one.env} + many: {command: ["/many"], env_file: [/run/a.env, /run/b.env]} +`)) + if err != nil { + t.Fatal(err) + } + if got := []string(s.Services["one"].EnvFiles); !reflect.DeepEqual(got, []string{"/run/one.env"}) { + t.Fatalf("one = %v", got) + } + if got := []string(s.Services["many"].EnvFiles); !reflect.DeepEqual(got, []string{"/run/a.env", "/run/b.env"}) { + t.Fatalf("many = %v", got) + } + if _, _, err := load(writeSpec(t, ` +services: + rel: {command: ["/rel"], env_file: relative.env} +`)); err == nil { + t.Fatal("a relative env_file must be rejected") + } +} + +func TestWaitEnvFilesWaitsForTheFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "router.env") + svc := &service{name: "router", EnvFiles: envFiles{path}} + go func() { + time.Sleep(400 * time.Millisecond) + _ = os.WriteFile(path, []byte("# written by the gateway\nDATABASE_URL=postgres://u@127.0.0.1:5432/db?options=a=b\n\nTYPESAFE_API_KEY=k\n"), 0o600) + }() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + env, err := waitEnvFiles(ctx, svc) + if err != nil { + t.Fatal(err) + } + want := []string{"DATABASE_URL=postgres://u@127.0.0.1:5432/db?options=a=b", "TYPESAFE_API_KEY=k"} + if !reflect.DeepEqual(env, want) { + t.Fatalf("env = %v, want %v", env, want) + } +} + +func TestWaitEnvFilesStopsWithContext(t *testing.T) { + svc := &service{name: "router", EnvFiles: envFiles{filepath.Join(t.TempDir(), "never.env")}} + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + if _, err := waitEnvFiles(ctx, svc); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("err = %v, want the context's error", err) + } +} + +func TestReadEnvFileRejectsMalformedLines(t *testing.T) { + for name, body := range map[string]string{ + "no equals": "DATABASE_URL\n", + "empty key": "=value\n", + "spaced key": " KEY=value\n", + } { + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "bad.env") + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + if _, err := readEnvFile(path); err == nil { + t.Fatal("want an error") + } + }) + } +} + +func TestEnvironmentOverridesEnvFile(t *testing.T) { + svc := &service{ + name: "printenv", + Command: []string{"/usr/bin/env"}, + Env: map[string]string{"PORT": "8083"}, + } + cmd, err := start(svc, []string{"PORT=9999", "FROM_FILE=yes"}) + if err != nil { + t.Fatal(err) + } + _ = cmd.Wait() + got := map[string]string{} + for _, kv := range cmd.Env { + key, value, _ := strings.Cut(kv, "=") + got[key] = value // last one wins, as exec does + } + if got["PORT"] != "8083" || got["FROM_FILE"] != "yes" { + t.Fatalf("PORT=%q FROM_FILE=%q", got["PORT"], got["FROM_FILE"]) + } +} diff --git a/apps/gateway/enclave/services.yaml b/apps/gateway/enclave/services.yaml index 1a2cf14..a1cb8a8 100644 --- a/apps/gateway/enclave/services.yaml +++ b/apps/gateway/enclave/services.yaml @@ -1,7 +1,8 @@ # 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. +# changes PCR0. Keys that are not Compose's: health, inherit_env. env_file is +# Compose's, except that the init waits for a file that does not exist yet. services: presidio: # One worker holds about 0.75 GiB (spaCy en_core_web_lg). Each extra @@ -24,3 +25,33 @@ services: PORT: "8080" PII_FILTER_ENABLED: "true" PRESIDIO_ANALYZER_URL: http://127.0.0.1:3000 + ROUTER_URL: http://127.0.0.1:8083 + + router: + # dappnode-nexus-router at the commit pinned in Dockerfile.enclave: the + # same code as the regular Router. It reads routing configuration from + # Postgres and, for Jev routers, asks TypeSafe to classify the request. + # It has no network of its own; both go through relays the gateway runs on + # loopback (apps/gateway/internal/enclave/network/relay.go). The admin API + # stays off (no ROUTER_ADMIN_TOKEN), so nothing in the enclave writes + # routing configuration. + command: ["/opt/nexus-router/router"] + working_dir: /opt/nexus-router + user: 1002 + depends_on: [gateway] + # DATABASE_URL and TYPESAFE_API_KEY. The gateway writes this file from the + # KMS-sealed bundle once the enclave has received it. + env_file: /run/nexus/router.env + environment: + PORT: "8083" + LOG_LEVEL: info + ONNXRUNTIME_SHARED_LIBRARY_PATH: /opt/nexus-router/lib/libonnxruntime.so + ROUTER_EMBEDDING_MODEL_PATH: /opt/nexus-router/models/model.onnx + ROUTER_EMBEDDING_TOKENIZER_PATH: /opt/nexus-router/models/tokenizer.json + ROUTER_EMBEDDING_MAX_TOKENS: "128" + # The Router's only way out for HTTPS: a CONNECT proxy that opens + # tunnels to TypeSafe and nothing else. + HTTPS_PROXY: http://127.0.0.1:3128 + health: + url: http://127.0.0.1:8083/healthz + timeout_seconds: 180 diff --git a/apps/gateway/internal/enclave/network/network_default.go b/apps/gateway/internal/enclave/network/network_default.go index 3f7f026..b774cb7 100644 --- a/apps/gateway/internal/enclave/network/network_default.go +++ b/apps/gateway/internal/enclave/network/network_default.go @@ -18,6 +18,12 @@ func ConfigureMeteringTransport(*http.Transport) {} func ConfigureRouterTransport(*http.Transport) {} +// StartRouterRelays only exists inside the enclave, where the Router has no +// network of its own. +func StartRouterRelays() ([]net.Listener, error) { + return nil, fmt.Errorf("router relays only exist inside the enclave") +} + func ConfigureDefaultTransport() error { return nil } func StartTinfoilTLSBridge() (net.Listener, error) { return nil, nil } diff --git a/apps/gateway/internal/enclave/network/network_nitro.go b/apps/gateway/internal/enclave/network/network_nitro.go index 6e9e25a..7bf1102 100644 --- a/apps/gateway/internal/enclave/network/network_nitro.go +++ b/apps/gateway/internal/enclave/network/network_nitro.go @@ -11,6 +11,7 @@ import ( "net/http" "strconv" "strings" + "time" "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/profile" "github.com/mdlayher/vsock" @@ -41,8 +42,54 @@ func ConfigureMeteringTransport(transport *http.Transport) { configureTransport(transport, profile.MeteringVsockPort) } +// ConfigureRouterTransport limits Router calls to loopback: the Router runs +// inside the enclave, and a request routed anywhere else would carry the +// prompt out of it. func ConfigureRouterTransport(transport *http.Transport) { - configureTransport(transport, profile.RouterVsockPort) + transport.Proxy = nil + dialer := &net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second} + transport.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) + } +} + +// StartRouterRelays opens the in-enclave Router's two ways out (see +// RouterDatabaseAddress and RouterEgressProxyAddress). Close the returned +// listeners to stop them. +func StartRouterRelays() ([]net.Listener, error) { + database, err := net.Listen("tcp4", RouterDatabaseAddress) + if err != nil { + return nil, fmt.Errorf("listen for the Router's database connections: %w", err) + } + routes := make(map[string]DialFunc, len(RouterEgressHosts)) + for _, host := range RouterEgressHosts { + port, err := providerVsockPort(host) + if err != nil { + database.Close() + return nil, fmt.Errorf("resolve Router egress route: %w", err) + } + routes[host] = vsockDialer(port) + } + proxy, err := net.Listen("tcp4", RouterEgressProxyAddress) + if err != nil { + database.Close() + return nil, fmt.Errorf("listen for the Router's egress proxy: %w", err) + } + go ServeTCPRelay(database, "database", vsockDialer(profile.DatabaseVsockPort)) + go ServeConnectProxy(proxy, routes) + return []net.Listener{database, proxy}, nil +} + +func vsockDialer(port uint32) DialFunc { + return func(ctx context.Context) (net.Conn, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + return vsock.Dial(profile.ParentCID, port, nil) + } } // ConfigureDefaultTransport routes package-level HTTP clients through the diff --git a/apps/gateway/internal/enclave/network/network_nitro_test.go b/apps/gateway/internal/enclave/network/network_nitro_test.go index f79292e..cb78049 100644 --- a/apps/gateway/internal/enclave/network/network_nitro_test.go +++ b/apps/gateway/internal/enclave/network/network_nitro_test.go @@ -122,3 +122,14 @@ func TestConfigureDefaultTransportInstallsFailClosedDialer(t *testing.T) { t.Fatal("provider vsock dialer was not installed") } } + +func TestRouterTransportOnlyDialsLoopback(t *testing.T) { + transport := http.DefaultTransport.(*http.Transport).Clone() + ConfigureRouterTransport(transport) + for _, address := range []string{"10.200.200.31:8083", "router.example.com:443", "[::1]:8083"} { + if _, err := transport.DialContext(context.Background(), "tcp", address); err == nil || + !strings.Contains(err.Error(), "loopback") { + t.Fatalf("dial %s: %v, want a loopback refusal", address, err) + } + } +} diff --git a/apps/gateway/internal/enclave/network/relay.go b/apps/gateway/internal/enclave/network/relay.go new file mode 100644 index 0000000..827cca4 --- /dev/null +++ b/apps/gateway/internal/enclave/network/relay.go @@ -0,0 +1,149 @@ +package network + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "strings" + "sync" + "time" +) + +// Loopback addresses the in-enclave Router uses to leave the enclave. The +// Router runs as its own unprivileged process and cannot open vsock +// connections, so the Gateway, which can, relays for it. Both listeners are +// bound to 127.0.0.1: inside an enclave nothing else can reach them. +const ( + // RouterDatabaseAddress is where the Router finds Postgres. The Gateway + // relays each connection to the parent over DatabaseVsockPort. + RouterDatabaseAddress = "127.0.0.1:5432" + // RouterEgressProxyAddress is an HTTP CONNECT proxy for the Router's + // HTTPS calls. It only opens tunnels to RouterEgressHosts, over the same + // measured provider routes the Gateway uses, and TLS still ends at the + // destination, so the parent sees ciphertext only. + RouterEgressProxyAddress = "127.0.0.1:3128" +) + +// RouterEgressHosts are the only destinations the Router may reach: TypeSafe, +// which its Jev strategy asks to classify a request. +var RouterEgressHosts = []string{"api.typesafe.ai:443"} + +// DialFunc opens the upstream side of a relayed connection. +type DialFunc func(ctx context.Context) (net.Conn, error) + +const relayDialTimeout = 10 * time.Second + +// ServeTCPRelay accepts connections on listener and joins each one to a new +// upstream connection from dial, until listener is closed. +func ServeTCPRelay(listener net.Listener, name string, dial DialFunc) { + for { + local, err := listener.Accept() + if err != nil { + if !errors.Is(err, net.ErrClosed) { + log.Printf("%s relay stopped: %v", name, err) + } + return + } + go func() { + defer local.Close() + ctx, cancel := context.WithTimeout(context.Background(), relayDialTimeout) + upstream, err := dial(ctx) + cancel() + if err != nil { + log.Printf("%s relay could not reach its upstream: %v", name, err) + return + } + defer upstream.Close() + join(local, upstream, nil) + }() + } +} + +// ServeConnectProxy is a minimal HTTP CONNECT proxy. Each CONNECT names a +// host:port; only keys of routes are accepted, and the tunnel is opened with +// that route's dialer. Anything else gets a 403 or 405 and is closed. The +// proxy never sees inside the tunnel: the client runs TLS through it. +func ServeConnectProxy(listener net.Listener, routes map[string]DialFunc) { + for { + conn, err := listener.Accept() + if err != nil { + if !errors.Is(err, net.ErrClosed) { + log.Printf("egress proxy stopped: %v", err) + } + return + } + go handleConnect(conn, routes) + } +} + +func handleConnect(conn net.Conn, routes map[string]DialFunc) { + defer conn.Close() + _ = conn.SetReadDeadline(time.Now().Add(relayDialTimeout)) + reader := bufio.NewReader(conn) + request, err := http.ReadRequest(reader) + if err != nil { + return + } + _ = conn.SetReadDeadline(time.Time{}) + if request.Method != http.MethodConnect { + writeProxyStatus(conn, http.StatusMethodNotAllowed) + return + } + dial, ok := routes[strings.ToLower(request.Host)] + if !ok { + log.Printf("egress proxy refused a tunnel to %q", request.Host) + writeProxyStatus(conn, http.StatusForbidden) + return + } + ctx, cancel := context.WithTimeout(context.Background(), relayDialTimeout) + upstream, err := dial(ctx) + cancel() + if err != nil { + log.Printf("egress proxy could not reach %s: %v", request.Host, err) + writeProxyStatus(conn, http.StatusBadGateway) + return + } + defer upstream.Close() + if _, err := io.WriteString(conn, "HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil { + return + } + // The client may have sent its TLS ClientHello right behind the CONNECT; + // the reader can hold those bytes already. + join(conn, upstream, reader) +} + +func writeProxyStatus(conn net.Conn, status int) { + _, _ = fmt.Fprintf(conn, "HTTP/1.1 %d %s\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", status, http.StatusText(status)) +} + +// join copies both ways until either side ends, then closes both. buffered, +// when set, is read from instead of local for the local-to-upstream direction. +func join(local, upstream net.Conn, buffered io.Reader) { + from := io.Reader(local) + if buffered != nil { + from = buffered + } + var once sync.Once + closeBoth := func() { + local.Close() + upstream.Close() + } + done := make(chan struct{}, 2) + go func() { + _, _ = io.Copy(upstream, from) + once.Do(closeBoth) + done <- struct{}{} + }() + go func() { + _, _ = io.Copy(local, upstream) + once.Do(closeBoth) + done <- struct{}{} + }() + <-done + <-done +} diff --git a/apps/gateway/internal/enclave/network/relay_test.go b/apps/gateway/internal/enclave/network/relay_test.go new file mode 100644 index 0000000..f954acf --- /dev/null +++ b/apps/gateway/internal/enclave/network/relay_test.go @@ -0,0 +1,176 @@ +package network + +import ( + "bufio" + "context" + "errors" + "io" + "net" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" +) + +// echoUpstream returns a dialer to a server that echoes what it receives with +// a prefix, and counts how many times it was dialled. +func echoUpstream(t *testing.T, prefix string) (DialFunc, *atomic.Int32) { + t.Helper() + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go func() { + defer conn.Close() + scanner := bufio.NewScanner(conn) + for scanner.Scan() { + if _, err := io.WriteString(conn, prefix+scanner.Text()+"\n"); err != nil { + return + } + } + }() + } + }() + dials := new(atomic.Int32) + return func(ctx context.Context) (net.Conn, error) { + dials.Add(1) + var d net.Dialer + return d.DialContext(ctx, "tcp4", listener.Addr().String()) + }, dials +} + +func serve(t *testing.T, run func(net.Listener)) string { + t.Helper() + listener, err := net.Listen("tcp4", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { listener.Close() }) + go run(listener) + return listener.Addr().String() +} + +func dial(t *testing.T, address string) (net.Conn, *bufio.Reader) { + t.Helper() + conn, err := net.DialTimeout("tcp4", address, 2*time.Second) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { conn.Close() }) + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + return conn, bufio.NewReader(conn) +} + +func TestTCPRelayJoinsBothDirections(t *testing.T) { + upstream, _ := echoUpstream(t, "db:") + address := serve(t, func(l net.Listener) { ServeTCPRelay(l, "database", upstream) }) + conn, reader := dial(t, address) + for _, line := range []string{"SELECT 1", "SELECT 2"} { + if _, err := io.WriteString(conn, line+"\n"); err != nil { + t.Fatal(err) + } + got, err := reader.ReadString('\n') + if err != nil || got != "db:"+line+"\n" { + t.Fatalf("got %q, %v", got, err) + } + } +} + +func TestTCPRelayClosesWhenUpstreamIsUnreachable(t *testing.T) { + address := serve(t, func(l net.Listener) { + ServeTCPRelay(l, "database", func(context.Context) (net.Conn, error) { + return nil, errors.New("parent relay down") + }) + }) + _, reader := dial(t, address) + if _, err := reader.ReadByte(); err == nil { + t.Fatal("want the connection closed") + } +} + +func TestConnectProxyTunnelsOnlyAllowedHosts(t *testing.T) { + upstream, dials := echoUpstream(t, "typesafe:") + address := serve(t, func(l net.Listener) { + ServeConnectProxy(l, map[string]DialFunc{"api.typesafe.ai:443": upstream}) + }) + + t.Run("allowed host, data sent right behind the CONNECT", func(t *testing.T) { + conn, reader := dial(t, address) + // The client's first bytes can arrive in the same read as the CONNECT. + if _, err := io.WriteString(conn, "CONNECT API.TypeSafe.ai:443 HTTP/1.1\r\nHost: api.typesafe.ai:443\r\n\r\nhello\n"); err != nil { + t.Fatal(err) + } + response, err := http.ReadResponse(reader, nil) + if err != nil || response.StatusCode != http.StatusOK { + t.Fatalf("CONNECT response: %v, %v", response, err) + } + got, err := reader.ReadString('\n') + if err != nil || got != "typesafe:hello\n" { + t.Fatalf("got %q, %v", got, err) + } + }) + + for name, request := range map[string]string{ + "other host": "CONNECT api.deepseek.com:443 HTTP/1.1\r\nHost: api.deepseek.com:443\r\n\r\n", + "other port": "CONNECT api.typesafe.ai:80 HTTP/1.1\r\nHost: api.typesafe.ai:80\r\n\r\n", + "plain proxy request": "GET http://api.typesafe.ai/ HTTP/1.1\r\nHost: api.typesafe.ai\r\n\r\n", + } { + t.Run(name, func(t *testing.T) { + before := dials.Load() + conn, reader := dial(t, address) + if _, err := io.WriteString(conn, request); err != nil { + t.Fatal(err) + } + response, err := http.ReadResponse(reader, nil) + if err != nil { + t.Fatal(err) + } + if response.StatusCode == http.StatusOK { + t.Fatal("tunnel opened") + } + if dials.Load() != before { + t.Fatal("upstream was dialled for a refused request") + } + if _, err := reader.ReadByte(); err == nil { + t.Fatal("want the connection closed") + } + }) + } +} + +func TestConnectProxyReportsUnreachableUpstream(t *testing.T) { + address := serve(t, func(l net.Listener) { + ServeConnectProxy(l, map[string]DialFunc{"api.typesafe.ai:443": func(context.Context) (net.Conn, error) { + return nil, errors.New("parent relay down") + }}) + }) + conn, reader := dial(t, address) + if _, err := io.WriteString(conn, "CONNECT api.typesafe.ai:443 HTTP/1.1\r\nHost: api.typesafe.ai:443\r\n\r\n"); err != nil { + t.Fatal(err) + } + response, err := http.ReadResponse(reader, nil) + if err != nil || response.StatusCode != http.StatusBadGateway { + t.Fatalf("response %v, %v", response, err) + } +} + +func TestRouterRelayAddressesAreLoopback(t *testing.T) { + for _, address := range []string{RouterDatabaseAddress, RouterEgressProxyAddress} { + if err := CheckLoopbackAddress(address); err != nil { + t.Fatal(err) + } + } + for _, host := range RouterEgressHosts { + if !strings.HasSuffix(host, ":443") { + t.Fatalf("Router egress %q is not HTTPS", host) + } + } +} diff --git a/apps/gateway/internal/enclave/profile/manifest.go b/apps/gateway/internal/enclave/profile/manifest.go index 9ba0fdd..84ee6e5 100644 --- a/apps/gateway/internal/enclave/profile/manifest.go +++ b/apps/gateway/internal/enclave/profile/manifest.go @@ -14,7 +14,10 @@ const ( ParentCID = 3 KMSVsockPort = 8000 MeteringVsockPort = 8444 - RouterVsockPort = 8445 + // DatabaseVsockPort carries the in-enclave Router's Postgres connection to + // the parent, which relays it to the Nexus database. The Router only reads + // routing configuration over it; prompts never cross it. + DatabaseVsockPort = 8455 // MetricsVsockPort serves Prometheus metrics to the parent, which forwards // them to the scraper. The parent connects in, so this adds no way out of // the enclave. Metrics carry model, provider and error labels, never @@ -81,7 +84,7 @@ type egressProfile struct { KMSVsockPort uint32 `json:"kms_vsock_port"` ProviderRoutes []ProviderEgressRoute `json:"provider_routes"` MeteringVsockPort uint32 `json:"metering_vsock_port"` - RouterVsockPort uint32 `json:"router_vsock_port"` + DatabaseVsockPort uint32 `json:"database_vsock_port"` } type ingressProfile struct { @@ -119,7 +122,7 @@ func ManifestJSON() []byte { KMSVsockPort: KMSVsockPort, ProviderRoutes: ProviderEgressRoutes(), MeteringVsockPort: MeteringVsockPort, - RouterVsockPort: RouterVsockPort, + DatabaseVsockPort: DatabaseVsockPort, }, Ingress: ingressProfile{ GatewayVsockPort: GatewayPort, diff --git a/apps/gateway/internal/enclave/profile/manifest_test.go b/apps/gateway/internal/enclave/profile/manifest_test.go index 1db4759..daec024 100644 --- a/apps/gateway/internal/enclave/profile/manifest_test.go +++ b/apps/gateway/internal/enclave/profile/manifest_test.go @@ -26,6 +26,12 @@ func TestManifestDigestCoversBuildPolicy(t *testing.T) { if !ok || egress["parent_cid"] != float64(ParentCID) { t.Fatalf("manifest does not declare the Nitro parent CID: %s", manifestJSON) } + if egress["database_vsock_port"] != float64(DatabaseVsockPort) { + t.Fatalf("manifest does not declare the Router's database relay: %s", manifestJSON) + } + if _, ok := egress["router_vsock_port"]; ok { + t.Fatalf("the Router runs inside the enclave; no Router egress may be declared: %s", manifestJSON) + } routes, ok := egress["provider_routes"].([]any) if !ok || len(routes) != len(ProviderEgressRoutes()) { t.Fatalf("manifest does not declare every provider egress route: %s", manifestJSON) @@ -92,3 +98,24 @@ func setTestBuildValues() func() { KMSKeyARN = previousKMSKeyARN } } + +// Every vsock port the enclave dials on the parent must be distinct: two +// routes on one port would send one destination's traffic to the other's +// proxy. A merge can introduce a clash without any textual conflict. (Ports +// the enclave listens on, such as GatewayPort, are on the enclave's own CID.) +func TestParentVsockPortsAreDistinct(t *testing.T) { + owners := map[uint32]string{ + KMSVsockPort: "kms", + MeteringVsockPort: "metering", + } + add := func(port uint32, name string) { + if other, ok := owners[port]; ok { + t.Fatalf("vsock port %d is used by both %s and %s", port, other, name) + } + owners[port] = name + } + add(DatabaseVsockPort, "database") + for _, route := range ProviderEgressRoutes() { + add(route.VsockPort, "provider "+route.Name) + } +} diff --git a/apps/gateway/internal/enclave/routerservice/routerservice.go b/apps/gateway/internal/enclave/routerservice/routerservice.go new file mode 100644 index 0000000..8ee4e9c --- /dev/null +++ b/apps/gateway/internal/enclave/routerservice/routerservice.go @@ -0,0 +1,106 @@ +// Package routerservice hands the in-enclave Router the settings that arrive +// in the KMS-sealed secret bundle. +// +// Only the Gateway can decrypt the bundle: KMS releases it to the Gateway's +// attested bootstrap. The Router is a separate process started by +// nexus-enclave-init, so once the bundle is in, the Gateway writes the +// Router's share of it to EnvFile and the init passes that file to the Router +// as its environment (services.yaml `env_file`). +package routerservice + +import ( + "errors" + "fmt" + "net" + "net/url" + "os" + "path/filepath" + "sort" + "strings" + + enclavenetwork "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/network" +) + +// EnvFile is where the Router's secrets are written. /run is the enclave's +// RAM; the directory and file are readable by root only, and the init (root) +// reads it to start the Router. +const EnvFile = "/run/nexus/router.env" + +// Environment returns the Router's secret settings from the decrypted bundle: +// the database URL, which must point at the in-enclave relay, and the TypeSafe +// key its Jev strategy needs (optional, as on an ordinary Router). +func Environment(getenv func(string) string) (map[string]string, error) { + databaseURL := strings.TrimSpace(getenv("ROUTER_DATABASE_URL")) + if databaseURL == "" { + return nil, errors.New("ROUTER_DATABASE_URL is required inside the enclave") + } + if err := checkDatabaseURL(databaseURL); err != nil { + return nil, err + } + env := map[string]string{"DATABASE_URL": databaseURL} + if key := strings.TrimSpace(getenv("TYPESAFE_API_KEY")); key != "" { + env["TYPESAFE_API_KEY"] = key + } + return env, nil +} + +// checkDatabaseURL accepts only a Postgres URL whose host is the enclave's +// database relay, so a bundle cannot point the Router anywhere else. +func checkDatabaseURL(raw string) error { + parsed, err := url.Parse(raw) + if err != nil || (parsed.Scheme != "postgres" && parsed.Scheme != "postgresql") { + return errors.New("ROUTER_DATABASE_URL must be a postgres:// URL") + } + if parsed.Host != enclavenetwork.RouterDatabaseAddress { + host, port, _ := net.SplitHostPort(parsed.Host) + return fmt.Errorf("ROUTER_DATABASE_URL must connect to %s, the enclave's database relay (got host %q port %q)", + enclavenetwork.RouterDatabaseAddress, host, port) + } + if strings.Trim(parsed.Path, "/") == "" { + return errors.New("ROUTER_DATABASE_URL must name a database") + } + return nil +} + +// WriteEnvFile replaces path with env as sorted KEY=VALUE lines, readable by +// root only. It writes a temporary file and renames it, so a reader never +// sees a partial file. +func WriteEnvFile(path string, env map[string]string) error { + keys := make([]string, 0, len(env)) + for key, value := range env { + if key == "" || strings.ContainsAny(key, "=\n\r") { + return fmt.Errorf("invalid environment key %q", key) + } + if strings.ContainsAny(value, "\n\r\x00") { + return fmt.Errorf("environment value for %s contains a line break or NUL", key) + } + keys = append(keys, key) + } + sort.Strings(keys) + var body strings.Builder + for _, key := range keys { + body.WriteString(key + "=" + env[key] + "\n") + } + + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + tmp, err := os.CreateTemp(dir, ".router-env-*") + if err != nil { + return fmt.Errorf("create temporary env file: %w", err) + } + defer os.Remove(tmp.Name()) + if err := tmp.Chmod(0o600); err != nil { + tmp.Close() + return err + } + if _, err := tmp.WriteString(body.String()); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmp.Name(), path) +} diff --git a/apps/gateway/internal/enclave/routerservice/routerservice_test.go b/apps/gateway/internal/enclave/routerservice/routerservice_test.go new file mode 100644 index 0000000..b2c9dfc --- /dev/null +++ b/apps/gateway/internal/enclave/routerservice/routerservice_test.go @@ -0,0 +1,139 @@ +package routerservice + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" + + enclavenetwork "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/network" + "github.com/dappnode/dappnode-nexus-gateway/internal/enclavebundle" +) + +func getenv(values map[string]string) func(string) string { + return func(key string) string { return values[key] } +} + +func TestEnvironmentPassesDatabaseAndTypeSafe(t *testing.T) { + env, err := Environment(getenv(map[string]string{ + "ROUTER_DATABASE_URL": "postgres://nexus@127.0.0.1:5432/nexus?sslmode=disable", + "TYPESAFE_API_KEY": "ts-key", + "METERING_TOKEN": "not for the router", + })) + if err != nil { + t.Fatal(err) + } + if len(env) != 2 || env["DATABASE_URL"] != "postgres://nexus@127.0.0.1:5432/nexus?sslmode=disable" || env["TYPESAFE_API_KEY"] != "ts-key" { + t.Fatalf("env = %v", env) + } +} + +func TestEnvironmentWithoutTypeSafe(t *testing.T) { + env, err := Environment(getenv(map[string]string{ + "ROUTER_DATABASE_URL": "postgres://nexus@127.0.0.1:5432/nexus", + })) + if err != nil { + t.Fatal(err) + } + if _, ok := env["TYPESAFE_API_KEY"]; ok { + t.Fatal("an empty TypeSafe key must not be passed") + } +} + +func TestEnvironmentRejectsDatabasesOutsideTheRelay(t *testing.T) { + for name, value := range map[string]string{ + "missing": "", + "other host": "postgres://nexus@10.200.200.31:5432/nexus", + "other port": "postgres://nexus@127.0.0.1:5433/nexus", + "name not ip": "postgres://nexus@localhost:5432/nexus", + "no port": "postgres://nexus@127.0.0.1/nexus", + "not postgres": "mysql://nexus:pw@127.0.0.1:5432/nexus", + "no database": "postgres://nexus@127.0.0.1:5432/", + "multiple hosts": "postgres://nexus@127.0.0.1:5432,10.0.0.1:5432/nexus", + "unparseable url": "postgres://%zz", + } { + t.Run(name, func(t *testing.T) { + if _, err := Environment(getenv(map[string]string{"ROUTER_DATABASE_URL": value})); err == nil { + t.Fatalf("accepted %q", value) + } + }) + } +} + +func TestWriteEnvFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "nexus", "router.env") + if err := WriteEnvFile(path, map[string]string{"B": "two=2", "A": "one"}); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(raw) != "A=one\nB=two=2\n" { + t.Fatalf("file = %q", raw) + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("file mode = %v, want 0600", info.Mode().Perm()) + } + dir, err := os.Stat(filepath.Dir(path)) + if err != nil { + t.Fatal(err) + } + if dir.Mode().Perm() != 0o700 { + t.Fatalf("directory mode = %v, want 0700", dir.Mode().Perm()) + } + + // Rewriting replaces the file and leaves no temporary files behind. + if err := WriteEnvFile(path, map[string]string{"A": "new"}); err != nil { + t.Fatal(err) + } + entries, _ := os.ReadDir(filepath.Dir(path)) + if len(entries) != 1 { + t.Fatalf("directory holds %d entries, want 1", len(entries)) + } +} + +func TestWriteEnvFileRejectsLineBreaks(t *testing.T) { + path := filepath.Join(t.TempDir(), "router.env") + for _, env := range []map[string]string{ + {"A": "one\nB=injected"}, + {"A": "carriage\rreturn"}, + {"A=B": "x"}, + {"": "x"}, + } { + if err := WriteEnvFile(path, env); err == nil { + t.Fatalf("accepted %v", env) + } + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatal("a rejected environment must not leave a file") + } +} + +// The bundle is validated against its own copy of the relay address; this +// keeps the two from drifting apart. +func TestBundleValidationAgreesOnTheRelayAddress(t *testing.T) { + now := time.Now().UTC() + databaseURL := "postgres://nexus@" + enclavenetwork.RouterDatabaseAddress + "/nexus" + bundle := enclavebundle.SecretBundle{ + SchemaVersion: enclavebundle.SchemaVersion, + SourceRevision: strings.Repeat("a", 40), + IssuedAt: now.Add(-time.Minute), + Environment: map[string]string{ + "METERING_URL": "https://metering.example.com", + "METERING_TOKEN": "secret", + "ROUTER_DATABASE_URL": databaseURL, + }, + } + if err := enclavebundle.ValidateSecretBundle(bundle, strings.Repeat("a", 40), now); err != nil { + t.Fatalf("the bundle rejects the relay address the gateway listens on: %v", err) + } + if _, err := Environment(getenv(map[string]string{"ROUTER_DATABASE_URL": databaseURL})); err != nil { + t.Fatal(err) + } +} diff --git a/apps/gateway/loopback_url_test.go b/apps/gateway/loopback_url_test.go new file mode 100644 index 0000000..5f4f76a --- /dev/null +++ b/apps/gateway/loopback_url_test.go @@ -0,0 +1,23 @@ +package main + +import "testing" + +func TestRequireLoopbackHTTP(t *testing.T) { + for _, ok := range []string{"http://127.0.0.1:8083", "http://127.0.0.1:3000/"} { + if err := requireLoopbackHTTP(ok); err != nil { + t.Fatalf("%s rejected: %v", ok, err) + } + } + for _, bad := range []string{ + "https://127.0.0.1:8083", + "http://localhost:8083", + "http://10.200.200.31:8083", + "http://127.0.0.1", + "http://router.example.com:8083", + "://bad", + } { + if err := requireLoopbackHTTP(bad); err == nil { + t.Fatalf("%s accepted", bad) + } + } +} diff --git a/apps/gateway/main.go b/apps/gateway/main.go index 71facee..d547817 100644 --- a/apps/gateway/main.go +++ b/apps/gateway/main.go @@ -31,6 +31,7 @@ import ( "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/bootstrap" enclavenetwork "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/network" "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/profile" + "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/enclave/routerservice" "github.com/dappnode/dappnode-nexus-gateway/pkg/fx" "github.com/dappnode/dappnode-nexus-gateway/pkg/observability/logger" "github.com/tinfoilsh/encrypted-http-body-protocol/identity" @@ -52,11 +53,36 @@ func main() { log.Fatalf("failed to configure Tinfoil enclave verification: %v", err) } defer tinfoilTLSBridge.Close() + + // The Router runs next to the Gateway and leaves the enclave only + // through these relays. Start them before handing the Router its + // settings: the init starts the Router as soon as the file exists. + routerRelays, err := enclavenetwork.StartRouterRelays() + if err != nil { + log.Fatalf("failed to start the Router's relays: %v", err) + } + for _, relay := range routerRelays { + defer relay.Close() + } + routerEnv, err := routerservice.Environment(os.Getenv) + if err != nil { + log.Fatalf("invalid Router configuration: %v", err) + } + if err := routerservice.WriteEnvFile(routerservice.EnvFile, routerEnv); err != nil { + log.Fatalf("failed to hand the Router its configuration: %v", err) + } } port := envOr("PORT", "8080") logLevel := envOr("LOG_LEVEL", "info") routerURL := envOr("ROUTER_URL", "http://localhost:8083") + if profile.Enabled { + // The Router reads the prompt; inside the enclave it must be the + // sibling process on loopback. + if err := requireLoopbackHTTP(routerURL); err != nil { + log.Fatalf("ROUTER_URL must be http://127.0.0.1: inside the enclave: %v", err) + } + } meteringURL := envOr("METERING_URL", "http://localhost:8084") meteringToken := envOr("METERING_TOKEN", "dev-metering-token") transportTimeouts, err := loadTransportTimeouts() @@ -274,9 +300,8 @@ func buildPIIFilter(log *logger.ZapLogger) (ports.PIIFilter, string, bool) { 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) + if err := requireLoopbackHTTP(url); err != nil { + log.Error("PRESIDIO_ANALYZER_URL must be http://127.0.0.1: inside the enclave", "analyzer_url", url, "error", err.Error()) os.Exit(1) } cfg.Transport = enclavenetwork.LoopbackTransport() @@ -284,6 +309,19 @@ func buildPIIFilter(log *logger.ZapLogger) (ports.PIIFilter, string, bool) { return presidio.NewAdapter(cfg), language, failOpen } +// requireLoopbackHTTP accepts only http://127.0.0.1: URLs: the services +// that read prompt text inside the enclave are reached on loopback alone. +func requireLoopbackHTTP(raw string) error { + parsed, err := neturl.Parse(raw) + if err != nil { + return err + } + if parsed.Scheme != "http" { + return fmt.Errorf("scheme %q is not http", parsed.Scheme) + } + return enclavenetwork.CheckLoopbackAddress(parsed.Host) +} + // positiveIntEnv reads a positive whole number from the environment. A set but // invalid value is an error, so a typo cannot silently loosen a limit. func positiveIntEnv(name string, fallback int) (int, error) { diff --git a/internal/enclavebundle/bundle.go b/internal/enclavebundle/bundle.go index 22a5928..3804578 100644 --- a/internal/enclavebundle/bundle.go +++ b/internal/enclavebundle/bundle.go @@ -32,6 +32,7 @@ var allowedEnvironmentKeys = map[string]struct{}{ "METERING_URL": {}, "METERING_TOKEN": {}, "ROUTER_URL": {}, + "ROUTER_DATABASE_URL": {}, "LOG_LEVEL": {}, "EUR_TO_USD_FALLBACK_RATE": {}, "PII_FILTER_ENABLED": {}, @@ -265,11 +266,40 @@ func ValidateSecretBundle(bundle SecretBundle, expectedRevision string, now time if strings.TrimSpace(bundle.Environment["METERING_TOKEN"]) == "" { return errors.New("METERING_TOKEN is required") } + // The Router runs inside the enclave (services.yaml), so a Router URL may + // only point at loopback: anything else would carry prompts out. if routerURL := strings.TrimSpace(bundle.Environment["ROUTER_URL"]); routerURL != "" { - if err := validateHTTPSURL("ROUTER_URL", routerURL); err != nil { + if err := validateLoopbackHTTPURL("ROUTER_URL", routerURL); err != nil { return err } } + if databaseURL := strings.TrimSpace(bundle.Environment["ROUTER_DATABASE_URL"]); databaseURL != "" { + if err := validateRouterDatabaseURL(databaseURL); err != nil { + return err + } + } + return nil +} + +// routerDatabaseRelay is where the enclave's Gateway relays the Router's +// Postgres connections to the parent (enclave/network.RouterDatabaseAddress). +const routerDatabaseRelay = "127.0.0.1:5432" + +func validateLoopbackHTTPURL(name, value string) error { + parsed, err := url.Parse(value) + if err != nil || parsed.Scheme != "http" || parsed.Hostname() != "127.0.0.1" || parsed.Port() == "" || + parsed.User != nil || parsed.Fragment != "" || strings.Trim(parsed.Path, "/") != "" { + return fmt.Errorf("%s must be http://127.0.0.1:: the service runs inside the enclave", name) + } + return nil +} + +func validateRouterDatabaseURL(value string) error { + parsed, err := url.Parse(value) + if err != nil || (parsed.Scheme != "postgres" && parsed.Scheme != "postgresql") || + parsed.Host != routerDatabaseRelay || strings.Trim(parsed.Path, "/") == "" { + return fmt.Errorf("ROUTER_DATABASE_URL must be postgres://:@%s/, the enclave's database relay", routerDatabaseRelay) + } return nil } diff --git a/internal/enclavebundle/bundle_test.go b/internal/enclavebundle/bundle_test.go index d7a90e9..4a90f06 100644 --- a/internal/enclavebundle/bundle_test.go +++ b/internal/enclavebundle/bundle_test.go @@ -81,6 +81,38 @@ func TestValidateSecretBundleRejectsUntrustedConfiguration(t *testing.T) { "METERING_TOKEN": "secret", }, }, + { + name: "router outside the enclave", + environment: map[string]string{ + "METERING_URL": "https://metering.example.com", + "METERING_TOKEN": "secret", + "ROUTER_URL": "https://router.example.com", + }, + }, + { + name: "router on loopback over a path", + environment: map[string]string{ + "METERING_URL": "https://metering.example.com", + "METERING_TOKEN": "secret", + "ROUTER_URL": "http://127.0.0.1:8083/elsewhere", + }, + }, + { + name: "router database outside the relay", + environment: map[string]string{ + "METERING_URL": "https://metering.example.com", + "METERING_TOKEN": "secret", + "ROUTER_DATABASE_URL": "postgres://nexus@10.200.200.31:5432/nexus", + }, + }, + { + name: "router database without a database name", + environment: map[string]string{ + "METERING_URL": "https://metering.example.com", + "METERING_TOKEN": "secret", + "ROUTER_DATABASE_URL": "postgres://nexus@127.0.0.1:5432", + }, + }, { name: "arbitrary process setting", environment: map[string]string{ @@ -104,3 +136,22 @@ func TestValidateSecretBundleRejectsUntrustedConfiguration(t *testing.T) { }) } } + +func TestValidateSecretBundleAcceptsInEnclaveRouter(t *testing.T) { + now := time.Now().UTC() + bundle := SecretBundle{ + SchemaVersion: SchemaVersion, + SourceRevision: testRevision, + IssuedAt: now.Add(-time.Minute), + Environment: map[string]string{ + "METERING_URL": "https://metering.example.com", + "METERING_TOKEN": "secret", + "ROUTER_URL": "http://127.0.0.1:8083", + "ROUTER_DATABASE_URL": "postgres://nexus@127.0.0.1:5432/nexus?sslmode=disable", + "TYPESAFE_API_KEY": "ts-key", + }, + } + if err := ValidateSecretBundle(bundle, testRevision, now); err != nil { + t.Fatalf("in-enclave Router configuration rejected: %v", err) + } +}