diff --git a/README.md b/README.md index 228c865..cbbe011 100644 --- a/README.md +++ b/README.md @@ -142,16 +142,30 @@ The Nitro confidential endpoint authenticates before storing replay IDs. Each account may retain at most 10,000 IDs during the three-minute replay window, shared across its API keys; excess requests return 429 with `confidential_request_limit_exceeded`. The process-wide limit remains 100,000. -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. +Live entries are never evicted to admit new requests. Nitro builds serve +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. Analyzer results are cached across requests (`PII_CACHE_ENTRIES`, +default 20,000), keyed by an HMAC-SHA256 of the mode, language and text under +a random per-process key; the cache holds those digests and entity offsets, +never the text. 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..f459781 --- /dev/null +++ b/apps/gateway/cmd/nexus-enclave-init/main.go @@ -0,0 +1,364 @@ +// 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. +var managedPIDs sync.Map + +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 { _, 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 + } + if err := cmd.Start(); err != nil { + return nil, err + } + managedPIDs.Store(cmd.Process.Pid, struct{}{}) + 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/cache/cache.go b/apps/gateway/internal/adapters/pii/cache/cache.go new file mode 100644 index 0000000..fa8e3de --- /dev/null +++ b/apps/gateway/internal/adapters/pii/cache/cache.go @@ -0,0 +1,140 @@ +// Package cache remembers PII analyzer results across requests. +// +// Chat clients resend the whole conversation on every turn, and the analyzer +// is called once per distinct text field. Without a shared cache, turn N of a +// conversation re-analyzes all N-1 earlier messages. The cache keys on an +// HMAC-SHA256 of the options and text under a random key drawn at start and +// kept only in memory, so it holds keyed digests and entity offsets, never the text, +// and its keys cannot be matched against guessed texts outside the process. +package cache + +import ( + "container/list" + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "sync" + "sync/atomic" + + "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/application/ports" + "github.com/dappnode/dappnode-nexus-gateway/pkg/domain" +) + +// DefaultEntries bounds the cache when no size is configured. An entry is a +// 32-byte key plus a few entity offsets, so this stays around a few megabytes. +const DefaultEntries = 20000 + +// Filter wraps a PII filter with a bounded least-recently-used cache. +type Filter struct { + next ports.PIIFilter + max int + secret []byte // HMAC key for cache keys; random per process. + + mu sync.Mutex + order *list.List // Front is the most recently used. + items map[[sha256.Size]byte]*list.Element + + hits atomic.Int64 + misses atomic.Int64 +} + +type entry struct { + key [sha256.Size]byte + entities []domain.PIIEntity +} + +// New returns next wrapped in a cache of at most maxEntries results. +func New(next ports.PIIFilter, maxEntries int) *Filter { + if maxEntries <= 0 { + maxEntries = DefaultEntries + } + secret := make([]byte, 32) + if _, err := rand.Read(secret); err != nil { + panic("pii cache: no randomness for the cache key: " + err.Error()) + } + return &Filter{ + next: next, + max: maxEntries, + secret: secret, + order: list.New(), + items: make(map[[sha256.Size]byte]*list.Element), + } +} + +// Enabled reports whether the wrapped filter is operational. +func (f *Filter) Enabled() bool { return f.next.Enabled() } + +// Analyze returns cached entities for text analyzed before with the same +// options, and asks the wrapped filter otherwise. Errors are never cached. +func (f *Filter) Analyze(ctx context.Context, text string, opts ports.PIIAnalyzeOptions) ([]domain.PIIEntity, error) { + if text == "" { + return nil, nil + } + key := f.cacheKey(text, opts) + if entities, ok := f.get(key); ok { + f.hits.Add(1) + return entities, nil + } + f.misses.Add(1) + entities, err := f.next.Analyze(ctx, text, opts) + if err != nil { + return nil, err + } + f.put(key, entities) + return clone(entities), nil +} + +// Stats returns how many lookups were answered from the cache and how many +// went to the analyzer. +func (f *Filter) Stats() (hits, misses int64) { + return f.hits.Load(), f.misses.Load() +} + +func (f *Filter) get(key [sha256.Size]byte) ([]domain.PIIEntity, bool) { + f.mu.Lock() + defer f.mu.Unlock() + el, ok := f.items[key] + if !ok { + return nil, false + } + f.order.MoveToFront(el) + return clone(el.Value.(*entry).entities), true +} + +func (f *Filter) put(key [sha256.Size]byte, entities []domain.PIIEntity) { + f.mu.Lock() + defer f.mu.Unlock() + if el, ok := f.items[key]; ok { + f.order.MoveToFront(el) + return + } + f.items[key] = f.order.PushFront(&entry{key: key, entities: clone(entities)}) + for f.order.Len() > f.max { + oldest := f.order.Back() + f.order.Remove(oldest) + delete(f.items, oldest.Value.(*entry).key) + } +} + +// cacheKey separates fields with a zero byte, which cannot appear in a mode +// or language code, so different option sets never share a key. +func (f *Filter) cacheKey(text string, opts ports.PIIAnalyzeOptions) [sha256.Size]byte { + h := hmac.New(sha256.New, f.secret) + h.Write([]byte(opts.Mode)) + h.Write([]byte{0}) + h.Write([]byte(opts.Language)) + h.Write([]byte{0}) + h.Write([]byte(text)) + var key [sha256.Size]byte + copy(key[:], h.Sum(nil)) + return key +} + +// clone keeps callers from changing what the cache holds. +func clone(entities []domain.PIIEntity) []domain.PIIEntity { + if entities == nil { + return nil + } + return append([]domain.PIIEntity(nil), entities...) +} diff --git a/apps/gateway/internal/adapters/pii/cache/cache_test.go b/apps/gateway/internal/adapters/pii/cache/cache_test.go new file mode 100644 index 0000000..86f3fae --- /dev/null +++ b/apps/gateway/internal/adapters/pii/cache/cache_test.go @@ -0,0 +1,98 @@ +package cache + +import ( + "context" + "errors" + "testing" + + "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/application/ports" + "github.com/dappnode/dappnode-nexus-gateway/pkg/domain" +) + +type countingFilter struct { + calls int + err error +} + +func (c *countingFilter) Enabled() bool { return true } + +func (c *countingFilter) Analyze(_ context.Context, text string, _ ports.PIIAnalyzeOptions) ([]domain.PIIEntity, error) { + c.calls++ + if c.err != nil { + return nil, c.err + } + return []domain.PIIEntity{{Type: "PERSON", Start: 0, End: len(text)}}, nil +} + +var balanced = ports.PIIAnalyzeOptions{Language: "en", Mode: domain.APIKeyPIIModeBalanced} + +func TestRepeatedTextIsAnalyzedOnce(t *testing.T) { + next := &countingFilter{} + f := New(next, 10) + for i := 0; i < 3; i++ { + got, err := f.Analyze(context.Background(), "Alice", balanced) + if err != nil || len(got) != 1 || got[0].End != 5 { + t.Fatalf("call %d: got %v, %v", i, got, err) + } + } + if next.calls != 1 { + t.Fatalf("analyzer calls = %d, want 1", next.calls) + } + if hits, misses := f.Stats(); hits != 2 || misses != 1 { + t.Fatalf("stats = %d hits, %d misses", hits, misses) + } +} + +func TestOptionsAreNotShared(t *testing.T) { + next := &countingFilter{} + f := New(next, 10) + _, _ = f.Analyze(context.Background(), "Alice", balanced) + _, _ = f.Analyze(context.Background(), "Alice", ports.PIIAnalyzeOptions{Language: "en", Mode: domain.APIKeyPIIModeHigh}) + _, _ = f.Analyze(context.Background(), "Alice", ports.PIIAnalyzeOptions{Language: "es", Mode: domain.APIKeyPIIModeBalanced}) + if next.calls != 3 { + t.Fatalf("analyzer calls = %d, want 3", next.calls) + } +} + +func TestErrorsAreNotCached(t *testing.T) { + next := &countingFilter{err: errors.New("down")} + f := New(next, 10) + if _, err := f.Analyze(context.Background(), "Alice", balanced); err == nil { + t.Fatal("want error") + } + next.err = nil + if _, err := f.Analyze(context.Background(), "Alice", balanced); err != nil { + t.Fatal(err) + } + if next.calls != 2 { + t.Fatalf("analyzer calls = %d, want 2", next.calls) + } +} + +func TestLeastRecentlyUsedIsEvicted(t *testing.T) { + next := &countingFilter{} + f := New(next, 2) + ctx := context.Background() + _, _ = f.Analyze(ctx, "a", balanced) + _, _ = f.Analyze(ctx, "b", balanced) + _, _ = f.Analyze(ctx, "a", balanced) // a is now the most recent + _, _ = f.Analyze(ctx, "c", balanced) // evicts b + _, _ = f.Analyze(ctx, "a", balanced) + if next.calls != 3 { + t.Fatalf("after eviction, analyzer calls = %d, want 3", next.calls) + } + _, _ = f.Analyze(ctx, "b", balanced) + if next.calls != 4 { + t.Fatalf("evicted text was not re-analyzed: calls = %d", next.calls) + } +} + +func TestCallersCannotChangeCachedEntities(t *testing.T) { + f := New(&countingFilter{}, 10) + got, _ := f.Analyze(context.Background(), "Alice", balanced) + got[0].Type = "CHANGED" + again, _ := f.Analyze(context.Background(), "Alice", balanced) + if again[0].Type != "PERSON" { + t.Fatalf("cached entity was changed through a returned slice: %v", again) + } +} 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/application/services/pii_cache_bench_test.go b/apps/gateway/internal/application/services/pii_cache_bench_test.go new file mode 100644 index 0000000..48b1480 --- /dev/null +++ b/apps/gateway/internal/application/services/pii_cache_bench_test.go @@ -0,0 +1,119 @@ +package services + +import ( + "context" + "encoding/json" + "fmt" + "math/rand" + "os" + "sort" + "strings" + "sync/atomic" + "testing" + "time" + + piicache "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/pii/cache" + "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/pii/presidio" + "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/application/ports" + "github.com/dappnode/dappnode-nexus-gateway/pkg/domain" +) + +// Measures PII masking on a growing agent conversation against a real +// Presidio analyzer, with and without the cross-request cache. Run with +// +// PRESIDIO_BENCH_URL=http://127.0.0.1:13001 go test -run TestPIICacheOnAgentConversation -v ./apps/gateway/internal/application/services +type countingPII struct { + next ports.PIIFilter + calls atomic.Int64 +} + +func (c *countingPII) Enabled() bool { return true } +func (c *countingPII) Analyze(ctx context.Context, text string, opts ports.PIIAnalyzeOptions) ([]domain.PIIEntity, error) { + c.calls.Add(1) + return c.next.Analyze(ctx, text, opts) +} + +var benchWords = strings.Fields("the deploy failed again because the config points at the old database host so " + + "please update the connection string restart the service and check the logs for errors before " + + "the review tomorrow the client asked for a summary of the changes and the test results") +var benchPII = []string{"John Smith", "maria.garcia@example.com", "+34 612 345 678", "Alice Johnson", "10.0.4.17", "Berlin"} + +func benchText(r *rand.Rand, n int) string { + var b strings.Builder + for b.Len() < n { + if r.Intn(25) == 0 { + b.WriteString(benchPII[r.Intn(len(benchPII))]) + } else { + b.WriteString(benchWords[r.Intn(len(benchWords))]) + } + b.WriteByte(' ') + } + return b.String() +} + +// benchConversation returns the request body of turn n: a system prompt and, +// per earlier turn, a user message, an assistant message with a tool call, +// and the tool's result. +func benchConversation(turns int) []byte { + r := rand.New(rand.NewSource(42)) + msgs := []map[string]any{{"role": "system", "content": benchText(r, 1500)}} + for i := 0; i < turns; i++ { + msgs = append(msgs, + map[string]any{"role": "user", "content": benchText(r, 300)}, + map[string]any{"role": "assistant", "content": benchText(r, 600), "tool_calls": []any{map[string]any{ + "id": fmt.Sprintf("call_%d", i), "type": "function", + "function": map[string]any{"name": "read_file", "arguments": fmt.Sprintf(`{"path":"/srv/app/%d.log","note":%q}`, i, benchText(r, 120))}, + }}}, + map[string]any{"role": "tool", "tool_call_id": fmt.Sprintf("call_%d", i), "content": benchText(r, 1500)}, + ) + } + body, _ := json.Marshal(map[string]any{"model": "x", "messages": msgs}) + return body +} + +func TestPIICacheOnAgentConversation(t *testing.T) { + url := os.Getenv("PRESIDIO_BENCH_URL") + if url == "" { + t.Skip("set PRESIDIO_BENCH_URL to run against a real analyzer") + } + const turns = 25 + lastBodies := map[bool][]byte{} + for _, cached := range []bool{false, true} { + counter := &countingPII{next: presidio.NewAdapter(presidio.Config{BaseURL: url, ScoreThreshold: 0.4, Timeout: 10 * time.Second})} + var filter ports.PIIFilter = counter + if cached { + filter = piicache.New(counter, 0) + } + svc, _ := piiService(filter, domain.APIKeyPIIModeBalanced, &stubProvider{}) + var perTurn []time.Duration + var total time.Duration + masked := 0 + for turn := 1; turn <= turns; turn++ { + body := benchConversation(turn) + start := time.Now() + out, mapping, err := svc.maskBody(context.Background(), body, domain.APIKeyPIIModeBalanced, domain.EndpointChatCompletions) + d := time.Since(start) + if err != nil { + t.Fatalf("turn %d: %v", turn, err) + } + if mapping != nil { + masked = mapping.Len() + } + if turn == turns { + lastBodies[cached] = out + } + perTurn = append(perTurn, d) + total += d + } + sorted := append([]time.Duration(nil), perTurn...) + sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] }) + t.Logf("cache=%v: %d analyzer calls over %d turns (%.1f per turn); masking time per turn p50 %s, last turn %s, total %s; last turn masked %d values", + cached, counter.calls.Load(), turns, float64(counter.calls.Load())/turns, + sorted[len(sorted)/2].Round(time.Millisecond), perTurn[len(perTurn)-1].Round(time.Millisecond), + total.Round(time.Millisecond), masked) + } + if string(lastBodies[false]) != string(lastBodies[true]) { + t.Fatal("the cache changed the masked request") + } + t.Log("masked request on the last turn is identical with and without the cache") +} 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..c49d121 --- /dev/null +++ b/apps/gateway/internal/enclave/network/loopback_test.go @@ -0,0 +1,33 @@ +package network + +import ( + "context" + "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 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..34db15b 100644 --- a/apps/gateway/internal/enclave/network/network_default.go +++ b/apps/gateway/internal/enclave/network/network_default.go @@ -21,3 +21,13 @@ 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 } + +// ListenMetrics is only used inside the enclave; elsewhere metrics listen on +// METRICS_PORT. +func ListenMetrics() (net.Listener, error) { + return nil, fmt.Errorf("metrics over vsock only exist inside the enclave") +} diff --git a/apps/gateway/internal/enclave/network/network_nitro.go b/apps/gateway/internal/enclave/network/network_nitro.go index c7e5f22..20275fd 100644 --- a/apps/gateway/internal/enclave/network/network_nitro.go +++ b/apps/gateway/internal/enclave/network/network_nitro.go @@ -27,6 +27,12 @@ func ListenGateway(port uint32) (net.Listener, error) { return vsock.Listen(port, nil) } +// ListenMetrics serves metrics on the measured vsock port the parent +// forwards to Prometheus. +func ListenMetrics() (net.Listener, error) { + return vsock.Listen(profile.MetricsVsockPort, nil) +} + func ConfigureProviderTransport(transport *http.Transport) { configureProviderTransport(transport) } @@ -77,6 +83,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/internal/enclave/profile/manifest.go b/apps/gateway/internal/enclave/profile/manifest.go index c7aa101..fc7b643 100644 --- a/apps/gateway/internal/enclave/profile/manifest.go +++ b/apps/gateway/internal/enclave/profile/manifest.go @@ -9,12 +9,17 @@ const ( // Port 7000 is used by the Nitro image loader while the enclave boots. // Keep application traffic on a distinct port to avoid relying on reuse of // that implementation-owned listener. - BootstrapPort = 7001 - GatewayPort = 8080 - ParentCID = 3 - KMSVsockPort = 8000 - MeteringVsockPort = 8444 - RouterVsockPort = 8445 + BootstrapPort = 7001 + GatewayPort = 8080 + ParentCID = 3 + KMSVsockPort = 8000 + MeteringVsockPort = 8444 + RouterVsockPort = 8445 + // MetricsVsockPort serves Prometheus metrics to the parent, which + // forwards them to the scraper. Metrics carry model, provider and error + // labels, never request content. The parent connects in, so this adds no + // way out of the enclave. + MetricsVsockPort = 9090 SecretBundleSchema = 1 ManifestSchema = 4 ) @@ -42,6 +47,8 @@ func ProviderEgressRoutes() []ProviderEgressRoute { {Name: "sigstore-tuf", Host: "tuf-repo-cdn.sigstore.dev", Port: 443, VsockPort: 8449}, {Name: "tinfoil-kds", Host: "kds-proxy.tinfoil.sh", Port: 443, VsockPort: 8450}, {Name: "tinfoil-tdx", Host: "tdx-proxy.tinfoil.sh", Port: 443, VsockPort: 8451}, + {Name: "dappnode", Host: "llm.dappnode.net", Port: 443, VsockPort: 8454}, + {Name: "frankfurter", Host: "api.frankfurter.dev", Port: 443, VsockPort: 8455}, } } diff --git a/apps/gateway/main.go b/apps/gateway/main.go index 719cee6..69754be 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" @@ -19,6 +20,7 @@ import ( "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/http/middleware" meteringadapter "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/metering" "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/observability/metrics" + piicache "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/pii/cache" "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/pii/presidio" "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/providers/openai" "github.com/dappnode/dappnode-nexus-gateway/apps/gateway/internal/adapters/providers/registry" @@ -168,11 +170,20 @@ func main() { go func() { metricsAddr := envOr("METRICS_PORT", "9090") zapLogger.Info("metrics server starting", "port", metricsAddr) - metricsBind := ":" + metricsAddr if profile.Enabled { - metricsBind = "127.0.0.1:" + metricsAddr + // Inside the enclave the parent forwards this vsock port to the + // scraper, so the enclave reports the same metrics as any gateway. + listener, err := enclavenetwork.ListenMetrics() + if err != nil { + zapLogger.Error("metrics listener error", "error", err) + return + } + if err := http.Serve(listener, metricsMux); err != nil { + zapLogger.Error("metrics server error", "error", err) + } + return } - if err := http.ListenAndServe(metricsBind, metricsMux); err != nil { + if err := http.ListenAndServe(":"+metricsAddr, metricsMux); err != nil { zapLogger.Error("metrics server error", "error", err) } }() @@ -254,13 +265,30 @@ 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() + } + entries, err := positiveIntEnv("PII_CACHE_ENTRIES", piicache.DefaultEntries) + if err != nil { + log.Error("invalid PII cache size", "error", err) + os.Exit(1) + } + log.Info("pii analyzer cache enabled", "entries", entries) + return piicache.New(presidio.NewAdapter(cfg), entries), 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 diff --git a/internal/enclavebundle/bundle.go b/internal/enclavebundle/bundle.go index 22a5928..f7df182 100644 --- a/internal/enclavebundle/bundle.go +++ b/internal/enclavebundle/bundle.go @@ -40,6 +40,8 @@ var allowedEnvironmentKeys = map[string]struct{}{ "PII_FILTER_SCORE_THRESHOLD": {}, "PII_FILTER_TIMEOUT_MS": {}, "PII_FILTER_FAIL_OPEN": {}, + "PII_CACHE_ENTRIES": {}, + "GUEST_MAX_OUTPUT_TOKENS": {}, "TINFOIL_PROXY_BASE_URL": {}, "TINFOIL_CONFIG_REPO": {}, "TINFOIL_ENCLAVE_HOST": {}, diff --git a/pkg/fx/frankfurter.go b/pkg/fx/frankfurter.go index 7dc9036..21abd82 100644 --- a/pkg/fx/frankfurter.go +++ b/pkg/fx/frankfurter.go @@ -11,7 +11,10 @@ import ( "time" ) -const frankfurterURL = "https://api.frankfurter.app/latest" +// frankfurterURL is the current endpoint. api.frankfurter.app now answers with +// a redirect here; calling it directly saves the round trip and lets the +// enclave allow a single measured host. +const frankfurterURL = "https://api.frankfurter.dev/v1/latest" // CacheTTL bounds how stale a cached rate may be. ECB publishes once per // business day, so an hour is comfortably fresh while sparing the API.