From 2096ae8267a14f2bc80066d311346f7a5b6a3325 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 14 Nov 2026 03:24:37 +1100 Subject: [PATCH] feat(openshell): each sandbox's network policy admits only what its task needs (#1864, #1967) Runtimes now take a task launch: image, mounts, env, the daemon's NATS and State Store with the task's credentials, its model providers and the hosts its tools may reach. Docker addresses them through the egress relay as before. An OpenShell sandbox reaches NATS and the State Store over plain TCP, the model providers with their credential bound, and the task's remote MCP hosts and the allowed package registries; services addressed by IP or loopback are named by the configured services host, since sandbox policy admits only DNS names. --- internal/app/archied/control_plane.go | 13 +- internal/app/archied/openshell.go | 9 +- internal/config/config.go | 8 + internal/config/egress_host.go | 38 ++++ internal/daemon/container_run.go | 89 ++++++--- internal/daemon/model_egress.go | 17 +- internal/daemon/pipeline.go | 2 +- internal/daemon/runtime.go | 43 +++- .../infrastructure/configuration/defaults.go | 12 ++ .../controlplanestore/container_settings.go | 40 ++-- internal/infrastructure/egress/sandbox_env.go | 17 +- .../infrastructure/openshell/policy_test.go | 110 +++++++++++ internal/infrastructure/openshell/runtime.go | 185 +++++++++++++++--- .../infrastructure/openshell/runtime_test.go | 4 +- 14 files changed, 507 insertions(+), 80 deletions(-) create mode 100644 internal/config/egress_host.go create mode 100644 internal/infrastructure/openshell/policy_test.go diff --git a/internal/app/archied/control_plane.go b/internal/app/archied/control_plane.go index 1a2c896e2..0a63bb03a 100644 --- a/internal/app/archied/control_plane.go +++ b/internal/app/archied/control_plane.go @@ -436,12 +436,23 @@ func (b *boot) refuseRuntimeChange(ctx context.Context) error { return nil } running := b.cfgHolder.Get().Containers - if runtimeName(stored.Runtime) != runtimeName(running.Runtime) || stored.OpenShell != running.OpenShell { + if runtimeName(stored.Runtime) != runtimeName(running.Runtime) || bootOnlyOpenShell(stored.OpenShell) != bootOnlyOpenShell(running.OpenShell) { return fmt.Errorf("the task runtime applies on restart: stored %q, running %q", runtimeName(stored.Runtime), runtimeName(running.Runtime)) } return nil } +// openShellBoot is the part of the OpenShell settings read once at boot; the +// egress hosts are read per task. +type openShellBoot struct { + address, workspace, servicesHost string + token config.SecretRef +} + +func bootOnlyOpenShell(c config.OpenShellConfig) openShellBoot { + return openShellBoot{address: c.Address, workspace: c.Workspace, servicesHost: c.ServicesHost, token: c.Token} +} + // runtimeName is runtime with the empty default spelled out. func runtimeName(runtime string) string { if runtime == "" { diff --git a/internal/app/archied/openshell.go b/internal/app/archied/openshell.go index 0bd9430b0..26bdaffe7 100644 --- a/internal/app/archied/openshell.go +++ b/internal/app/archied/openshell.go @@ -36,10 +36,11 @@ func startOpenShell(ctx context.Context, cfgHolder *config.Holder, secrets *secr return nil, nil, fmt.Errorf("openshell gateway %s: %w", settings.Address, err) } rt := openshell.New(client, openshell.Options{ - Workspace: settings.Workspace, - Instance: cfg.Instance, - MaxUptime: func() time.Duration { return cfgHolder.Get().Containers.MaxUptime.Std() }, - Log: log, + Workspace: settings.Workspace, + Instance: cfg.Instance, + ServicesHost: settings.ServicesHost, + MaxUptime: func() time.Duration { return cfgHolder.Get().Containers.MaxUptime.Std() }, + Log: log, }) checkCtx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() diff --git a/internal/config/config.go b/internal/config/config.go index 83832dcde..bfe2793f1 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -712,6 +712,14 @@ type OpenShellConfig struct { // Token resolves to the gateway's bearer token. Zero sends none, which // only a gateway allowing unauthenticated users accepts. Token SecretRef `toml:"token" yaml:"token" json:"token"` + // ServicesHost is the DNS name sandboxes reach this host's NATS and State + // Store by when those are addressed by IP or loopback: sandbox policy + // admits TCP only to DNS names, and never to loopback. + ServicesHost string `toml:"services_host" yaml:"services_host" json:"services_host"` + // EgressHosts are the hosts, "host" or "host:port" (443 by default), any + // tool in a sandbox may reach, such as package registries. A one-label + // wildcard ("*.example.com") matches subdomains. + EgressHosts []string `toml:"egress_hosts" yaml:"egress_hosts" json:"egress_hosts"` } // ContainerConfig configures Docker sandbox execution of archie-agent. diff --git a/internal/config/egress_host.go b/internal/config/egress_host.go new file mode 100644 index 000000000..4bb5b9f17 --- /dev/null +++ b/internal/config/egress_host.go @@ -0,0 +1,38 @@ +package config + +import ( + "fmt" + "net" + "strconv" + "strings" +) + +// EgressHost parses an egress host entry, "host" or "host:port", into its +// host and port; the port is 443 when none is given. The host is a DNS name, +// optionally with a whole first-label wildcard ("*.example.com") over at +// least three labels: sandbox policy names hosts, never addresses. +func EgressHost(entry string) (string, int, error) { + entry = strings.TrimSpace(entry) + host, port := entry, 443 + if h, p, err := net.SplitHostPort(entry); err == nil { + n, err := strconv.Atoi(p) + if err != nil || n < 1 || n > 65535 { + return "", 0, fmt.Errorf("egress host %q: port must be 1 to 65535", entry) + } + host, port = h, n + } + host = strings.ToLower(strings.TrimSuffix(host, ".")) + if host == "" || net.ParseIP(host) != nil { + return "", 0, fmt.Errorf("egress host %q: want a DNS name", entry) + } + labels := strings.Split(host, ".") + for i, label := range labels { + if label == "" || (strings.Contains(label, "*") && (i != 0 || label != "*")) { + return "", 0, fmt.Errorf("egress host %q: a wildcard must be the whole first label", entry) + } + } + if labels[0] == "*" && len(labels) < 3 { + return "", 0, fmt.Errorf("egress host %q: a wildcard host needs at least three labels", entry) + } + return host, port, nil +} diff --git a/internal/daemon/container_run.go b/internal/daemon/container_run.go index 676e7cccc..2a83e7086 100644 --- a/internal/daemon/container_run.go +++ b/internal/daemon/container_run.go @@ -5,7 +5,10 @@ import ( "encoding/json" "errors" "fmt" + "net" + "net/url" "os" + "slices" "strings" "time" @@ -33,7 +36,7 @@ func (d *Daemon) acquireTaskContainer( task *workflow.Task, repo config.Repo, workDir string, - image string, + profile config.AgentProfile, ) (TaskContainer, string, func(), bool) { park := func(reason string, err error) { d.Log.ErrorContext(ctx, reason, "err", err) @@ -96,15 +99,17 @@ func (d *Daemon) acquireTaskContainer( revokeRun := revokeCredential revokeCredential = func() { closeModel(); revokeRun() } - env, err := d.containerEnv(credential) - if err != nil { - revokeCredential() - d.teardownStorage(ctx, task, repo, workDir) - park("container environment failed", err) - return nil, "", nil, false - } - - ctr, err := d.Runtime.Acquire(ctx, image, append(mounts, model.Mounts...), append(env, model.Env...)) + ctr, err := d.Runtime.Acquire(ctx, TaskLaunch{ + Image: profile.Image, + Mounts: append(mounts, model.Mounts...), + // The agent may run as root in its container, so its commits land + // owned by UID 0 on the host. The daemon's UID/GID let it hand the + // worktree back before the daemon reads it to push. + Env: append([]string{fmt.Sprintf("WORKTREE_UID=%d", os.Getuid()), fmt.Sprintf("WORKTREE_GID=%d", os.Getgid())}, model.Env...), + Worker: d.workerEndpoints(credential), + Providers: model.Providers, + Hosts: d.taskEgressHosts(ctx, profile), + }) if err != nil { revokeCredential() // Roll back the storage we just set up: the mounts were created @@ -118,23 +123,63 @@ func (d *Daemon) acquireTaskContainer( return ctr, credential, revokeCredential, true } -// containerEnv is the environment a task container starts with. The container -// sits on a sandbox network whose only peer is the egress relay, so NATS and -// the State Store are the relay's ports; the credentials are this task's, -// never the daemon's own. NATS is the endpoint the daemon connected with at -// startup, not live config: a reloaded [nats] section must not point new -// containers at a server the daemon is not publishing on. -func (d *Daemon) containerEnv(stateStoreToken string) ([]string, error) { - // The agent runs as root in the container, so its commits land owned by - // UID 0 on the host. The daemon's UID/GID let the agent hand the worktree - // back before the daemon reads it to push. - return egress.WorkerEnv(egress.Endpoints{ +// workerEndpoints are NATS and the State Store as the daemon reaches them, +// with this task's credentials, never the daemon's own. NATS is the endpoint +// the daemon connected with at startup, not live config: a reloaded [nats] +// section must not point new containers at a server the daemon is not +// publishing on. +func (d *Daemon) workerEndpoints(stateStoreToken string) egress.Endpoints { + return egress.Endpoints{ NATS: d.ConnectedNATS.URL, NATSToken: d.ConnectedNATS.ContainerToken(), StateStore: d.ConnectedStateStore.URL, StateStoreToken: stateStoreToken, StateStoreCA: d.ConnectedStateStore.CA, - }, os.Getuid(), os.Getgid()) + } +} + +// taskEgressHosts are the hosts a task's tools may reach beyond archie: the +// remote MCP servers its profile allows, and the allowed package registries. +// An MCP server addressed by IP cannot be named in sandbox policy, so it is +// left out with a warning rather than failing every task. +func (d *Daemon) taskEgressHosts(ctx context.Context, profile config.AgentProfile) []string { + cfg := d.Cfg.Get() + hosts := slices.Clone(cfg.Containers.OpenShell.EgressHosts) + for _, server := range cfg.Tools.MCPServers { + if len(profile.Tools) > 0 && !slices.Contains(profile.Tools, server.Name) { + continue + } + for _, endpoint := range []string{server.URL, server.SSEEndpoint} { + host, ok := mcpEgressHost(endpoint) + if !ok { + if endpoint != "" { + d.Log.WarnContext(ctx, "mcp server cannot be reached from a sandbox: its url needs a DNS host name", "server", server.Name) + } + continue + } + if !slices.Contains(hosts, host) { + hosts = append(hosts, host) + } + } + } + return hosts +} + +// mcpEgressHost is a remote MCP endpoint's host:port, with the scheme's +// default port when none is given. +func mcpEgressHost(endpoint string) (string, bool) { + u, err := url.Parse(strings.TrimSpace(endpoint)) + if err != nil || u.Hostname() == "" || net.ParseIP(u.Hostname()) != nil { + return "", false + } + port := u.Port() + if port == "" { + port = "443" + if u.Scheme == "http" { + port = "80" + } + } + return net.JoinHostPort(u.Hostname(), port), true } // runCredential issues the task's run credential, or "" when no State Store diff --git a/internal/daemon/model_egress.go b/internal/daemon/model_egress.go index b85c284e8..7eec94091 100644 --- a/internal/daemon/model_egress.go +++ b/internal/daemon/model_egress.go @@ -45,10 +45,21 @@ func (d *Daemon) taskConfig(ctx context.Context, task *workflow.Task) (config.Co return cfg, nil } -// ModelSession is what a native container needs for its model proxy session. +// ModelSession is what a task's agent needs to call its model providers: +// environment and mounts for the Docker egress proxy, or the gateway +// providers an OpenShell sandbox attaches. type ModelSession struct { - Env []string - Mounts []storage.Mount + Env []string + Mounts []storage.Mount + Providers []ModelProvider +} + +// ModelProvider is a credentialed provider on an OpenShell gateway and the +// host its key may be sent to. +type ModelProvider struct { + Gateway string + Host string + Port int } // openModelEgress opens task's model session, or refuses: provider keys diff --git a/internal/daemon/pipeline.go b/internal/daemon/pipeline.go index 9a1bcc8f7..ada8b5075 100644 --- a/internal/daemon/pipeline.go +++ b/internal/daemon/pipeline.go @@ -79,7 +79,7 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task, hold *taskHol if !ok { return } - ctr, credential, revokeCredential, ok := d.acquireTaskContainer(ctx, task, repo, workDir, profile.Image) + ctr, credential, revokeCredential, ok := d.acquireTaskContainer(ctx, task, repo, workDir, profile) if !ok { return } diff --git a/internal/daemon/runtime.go b/internal/daemon/runtime.go index 243f74eaa..246e5cd9d 100644 --- a/internal/daemon/runtime.go +++ b/internal/daemon/runtime.go @@ -4,6 +4,7 @@ import ( "context" "github.com/samcharles93/archie-core/internal/container" + "github.com/samcharles93/archie-core/internal/infrastructure/egress" "github.com/samcharles93/archie-core/internal/infrastructure/openshell" "github.com/samcharles93/archie-core/internal/storage" ) @@ -11,8 +12,8 @@ import ( // TaskRuntime starts and stops the isolated environment a task's agent runs // in. The Docker container pool is one implementation. type TaskRuntime interface { - // Acquire starts the agent from image with mounts and env. - Acquire(ctx context.Context, image string, mounts []storage.Mount, env []string) (TaskContainer, error) + // Acquire starts the agent l describes. + Acquire(ctx context.Context, l TaskLaunch) (TaskContainer, error) // Release stops and removes a container Acquire returned. Release(ctx context.Context, c TaskContainer) // Reown hands dir back to uid:gid when a killed container left files the @@ -20,6 +21,23 @@ type TaskRuntime interface { Reown(ctx context.Context, dir string, uid, gid int) error } +// TaskLaunch is one task's agent: what it runs, and what it may reach. Each +// runtime turns the endpoints into the addresses its sandbox can use. +type TaskLaunch struct { + Image string + Mounts []storage.Mount + // Env is the agent's environment apart from its network endpoints. + Env []string + // Worker is NATS and the State Store as the daemon reaches them, with the + // task's credentials. + Worker egress.Endpoints + // Providers are the gateway providers the agent's model calls use. + Providers []ModelProvider + // Hosts are further hosts, "host" or "host:port", the agent's tools may + // reach: its remote MCP servers and the allowed package registries. + Hosts []string +} + // TaskContainer is one running task environment. type TaskContainer interface { // Exited closes when the agent stops running for any reason. @@ -39,8 +57,15 @@ func DockerRuntime(pool *container.Pool) TaskRuntime { type dockerRuntime struct{ pool *container.Pool } -func (r dockerRuntime) Acquire(ctx context.Context, image string, mounts []storage.Mount, env []string) (TaskContainer, error) { - c, err := r.pool.Acquire(ctx, image, mounts, env) +// Acquire starts a container on its sandbox network, where NATS and the State +// Store are the egress relay's ports. Model calls go through the egress proxy +// the session's env names; the container reaches nothing else. +func (r dockerRuntime) Acquire(ctx context.Context, l TaskLaunch) (TaskContainer, error) { + network, err := egress.WorkerEnv(l.Worker) + if err != nil { + return nil, err + } + c, err := r.pool.Acquire(ctx, l.Image, l.Mounts, append(network, l.Env...)) if err != nil { return nil, err } @@ -70,8 +95,14 @@ func OpenShellRuntime(rt *openshell.Runtime) TaskRuntime { type openShellRuntime struct{ rt *openshell.Runtime } -func (r openShellRuntime) Acquire(ctx context.Context, image string, mounts []storage.Mount, env []string) (TaskContainer, error) { - sb, err := r.rt.Acquire(ctx, image, mounts, env) +func (r openShellRuntime) Acquire(ctx context.Context, l TaskLaunch) (TaskContainer, error) { + providers := make([]openshell.Provider, 0, len(l.Providers)) + for _, p := range l.Providers { + providers = append(providers, openshell.Provider{Gateway: p.Gateway, Host: p.Host, Port: p.Port}) + } + sb, err := r.rt.Acquire(ctx, openshell.Launch{ + Image: l.Image, Mounts: l.Mounts, Env: l.Env, Worker: l.Worker, Providers: providers, Hosts: l.Hosts, + }) if err != nil { return nil, err } diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index ff3c497db..e6f028744 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -3,6 +3,7 @@ package configuration import ( "os" "path/filepath" + "slices" "strings" "time" @@ -336,4 +337,15 @@ func applyContainerDefaults(cfg *config.Config) { if cfg.Containers.PullPolicy == "" { cfg.Containers.PullPolicy = defaultPullPolicy } + // Nil, not empty: an operator who clears the list keeps it empty. + if cfg.Containers.OpenShell.EgressHosts == nil { + cfg.Containers.OpenShell.EgressHosts = slices.Clone(defaultEgressHosts) + } +} + +// defaultEgressHosts are the package registries the agent image's tools +// install from at run time: Go modules, npm, PyPI and uv's Python builds. +var defaultEgressHosts = []string{ + "proxy.golang.org", "sum.golang.org", "registry.npmjs.org", + "pypi.org", "files.pythonhosted.org", "github.com", "objects.githubusercontent.com", } diff --git a/internal/infrastructure/controlplanestore/container_settings.go b/internal/infrastructure/controlplanestore/container_settings.go index 14157b8f9..74ce70286 100644 --- a/internal/infrastructure/controlplanestore/container_settings.go +++ b/internal/infrastructure/controlplanestore/container_settings.go @@ -3,6 +3,7 @@ package controlplanestore import ( "encoding/json" "fmt" + "net" "strings" "github.com/samcharles93/archie-core/internal/config" @@ -111,17 +112,8 @@ func validateContainers(input []byte) error { if strings.TrimSpace(settings.Image) == "" { return fmt.Errorf("container image is required for autonomous workflow workers") } - switch settings.Runtime { - case "", config.RuntimeDocker: - case config.RuntimeOpenShell: - if strings.TrimSpace(settings.OpenShell.Address) == "" { - return fmt.Errorf("the openshell runtime needs a gateway address") - } - default: - return fmt.Errorf("runtime must be docker or openshell") - } - if (settings.OpenShell.Token.Engine == "") != (settings.OpenShell.Token.Key == "") { - return fmt.Errorf("the openshell token reference needs both an engine and a key") + if err := validateRuntime(settings); err != nil { + return err } // Profiles is json:"-" on config.ContainerConfig: it is // AgentProfileKind's document now, validated there. @@ -129,6 +121,32 @@ func validateContainers(input []byte) error { }) } +// validateRuntime checks the task runtime and, for OpenShell, its gateway +// settings. +func validateRuntime(settings config.ContainerConfig) error { + switch settings.Runtime { + case "", config.RuntimeDocker: + case config.RuntimeOpenShell: + if strings.TrimSpace(settings.OpenShell.Address) == "" { + return fmt.Errorf("the openshell runtime needs a gateway address") + } + default: + return fmt.Errorf("runtime must be docker or openshell") + } + if (settings.OpenShell.Token.Engine == "") != (settings.OpenShell.Token.Key == "") { + return fmt.Errorf("the openshell token reference needs both an engine and a key") + } + for _, host := range settings.OpenShell.EgressHosts { + if _, _, err := config.EgressHost(host); err != nil { + return err + } + } + if host := settings.OpenShell.ServicesHost; host != "" && net.ParseIP(host) != nil { + return fmt.Errorf("services_host must be a DNS name, not an IP address") + } + return nil +} + // normalizeContainerPolicies re-encodes the stored document with snake_case // keys. func normalizeContainerPolicies(input []byte) ([]byte, error) { diff --git a/internal/infrastructure/egress/sandbox_env.go b/internal/infrastructure/egress/sandbox_env.go index f07369deb..9dda57fbf 100644 --- a/internal/infrastructure/egress/sandbox_env.go +++ b/internal/infrastructure/egress/sandbox_env.go @@ -18,20 +18,27 @@ type Endpoints struct { StateStoreCA []byte } -// WorkerEnv is the worker's entire environment in a sandboxed container: NATS and +// WorkerEnv is the worker's network environment in a Docker sandbox: NATS and // the State Store at the relay's fixed ports, and the task's credentials. // Nothing else crosses, so no model provider key enters the container. -func WorkerEnv(e Endpoints, uid, gid int) ([]string, error) { +func WorkerEnv(e Endpoints) ([]string, error) { u, err := url.Parse(e.NATS) if err != nil || u.Scheme == "" { return nil, fmt.Errorf("nats url %q: want scheme://host:port", e.NATS) } - env := []string{"NATS_URL=" + u.Scheme + "://" + relayAddr(RelayNATSPort)} + return DirectWorkerEnv(u.Scheme+"://"+relayAddr(RelayNATSPort), relayAddr(RelayStateStorePort), e), nil +} + +// DirectWorkerEnv is the worker's network environment when it reaches NATS +// at nats and the State Store at stateStore itself, with the task's +// credentials from e. The State Store is left out when e names none. +func DirectWorkerEnv(nats, stateStore string, e Endpoints) []string { + env := []string{"NATS_URL=" + nats} if e.NATSToken != "" { env = append(env, "NATS_TOKEN="+e.NATSToken) } if e.StateStore != "" { - env = append(env, "STATE_STORE_URL="+relayAddr(RelayStateStorePort)) + env = append(env, "STATE_STORE_URL="+stateStore) if e.StateStoreToken != "" { env = append(env, "STATE_STORE_TOKEN="+e.StateStoreToken) } @@ -39,7 +46,7 @@ func WorkerEnv(e Endpoints, uid, gid int) ([]string, error) { env = append(env, "STATE_STORE_CA="+string(e.StateStoreCA)) } } - return append(env, "WORKTREE_UID="+strconv.Itoa(uid), "WORKTREE_GID="+strconv.Itoa(gid)), nil + return env } // relayTargets are the host:port addresses the relay forwards NATS and the diff --git a/internal/infrastructure/openshell/policy_test.go b/internal/infrastructure/openshell/policy_test.go new file mode 100644 index 000000000..d2507f39a --- /dev/null +++ b/internal/infrastructure/openshell/policy_test.go @@ -0,0 +1,110 @@ +package openshell + +import ( + "maps" + "slices" + "strconv" + "strings" + "testing" + + v1 "github.com/ai-openshell/sdk-go/openshell/v1" + + "github.com/samcharles93/archie-core/internal/infrastructure/egress" +) + +// TestSandboxPolicyAdmitsOnlyWhatTheTaskNeeds guards the sandbox's egress +// boundary: archie's own services and the model providers are open to the +// agent alone, extra hosts to any tool, nothing else is admitted, services +// addressed by IP or loopback are named by the services host, and no +// provider key enters the environment. +func TestSandboxPolicyAdmitsOnlyWhatTheTaskNeeds(t *testing.T) { + tests := []struct { + name string + servicesHost string + launch Launch + wantErr string + wantRules map[string]string // rule name -> "host:port binary" + wantEnv map[string]string + }{ + { + name: "services by IP and loopback use the services host", + servicesHost: "archie.lan", + launch: Launch{Worker: egress.Endpoints{ + NATS: "nats://172.17.0.1:4222", NATSToken: "t", StateStore: "dns:///127.0.0.1:50051", StateStoreToken: "run-1", + }}, + wantRules: map[string]string{ + "archie-nats": "archie.lan:4222 " + agentBinary, + "archie-state-store": "archie.lan:50051 " + agentBinary, + }, + wantEnv: map[string]string{ + "NATS_URL": "nats://archie.lan:4222", "NATS_TOKEN": "t", + "STATE_STORE_URL": "archie.lan:50051", "STATE_STORE_TOKEN": "run-1", + }, + }, + { + name: "services by DNS name, providers and extra hosts", + launch: Launch{ + Env: []string{"WORKTREE_UID=1000"}, + Worker: egress.Endpoints{NATS: "nats://nats.internal:4222"}, + Providers: []Provider{{Gateway: "task-7-anthropic", Host: "api.anthropic.com", Port: 443}}, + Hosts: []string{"proxy.golang.org", "mcp.lan:8443"}, + }, + wantRules: map[string]string{ + "archie-nats": "nats.internal:4222 " + agentBinary, + "model-task-7-anthropic": "api.anthropic.com:443 " + agentBinary, + "egress": "proxy.golang.org:443,mcp.lan:8443 " + anyBinary, + }, + wantEnv: map[string]string{"WORKTREE_UID": "1000", "NATS_URL": "nats://nats.internal:4222"}, + }, + { + name: "a service by IP with no services host is refused", + launch: Launch{Worker: egress.Endpoints{NATS: "nats://10.0.0.5:4222"}}, + wantErr: "services host", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rt := New(nil, Options{Instance: "archie", ServicesHost: tt.servicesHost}) + spec, err := rt.spec(tt.launch) + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("spec error = %v, want one mentioning %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatal(err) + } + got := map[string]string{} + for name, rule := range spec.Policy.NetworkPolicies { + var hosts, binaries []string + for _, e := range rule.Endpoints { + hosts = append(hosts, e.Host+":"+strconv.Itoa(int(e.Port))) + if strings.HasPrefix(name, "model-") && (e.CredentialBinding == nil || e.CredentialBinding.Provider != strings.TrimPrefix(name, "model-")) { + t.Errorf("rule %s does not bind its provider's credential", name) + } + if strings.HasPrefix(name, "archie-") && (e.Protocol != "tcp" || e.TLS != v1.NetworkTLSModeSkip) { + t.Errorf("rule %s is not plain TCP left uninspected", name) + } + } + for _, b := range rule.Binaries { + binaries = append(binaries, b.Path) + } + got[name] = strings.Join(hosts, ",") + " " + strings.Join(binaries, ",") + } + if !maps.Equal(got, tt.wantRules) { + t.Fatalf("rules = %v, want %v", got, tt.wantRules) + } + if !maps.Equal(spec.Environment, tt.wantEnv) { + t.Fatalf("environment = %v, want %v", spec.Environment, tt.wantEnv) + } + var providers []string + for _, p := range tt.launch.Providers { + providers = append(providers, p.Gateway) + } + if !slices.Equal(spec.Providers, providers) { + t.Fatalf("attached providers = %v, want %v", spec.Providers, providers) + } + }) + } +} diff --git a/internal/infrastructure/openshell/runtime.go b/internal/infrastructure/openshell/runtime.go index 66c8cc84d..082211d1a 100644 --- a/internal/infrastructure/openshell/runtime.go +++ b/internal/infrastructure/openshell/runtime.go @@ -8,13 +8,18 @@ import ( "errors" "fmt" "log/slog" + "net" "slices" + "strconv" "strings" "sync" "time" v1 "github.com/ai-openshell/sdk-go/openshell/v1" + "github.com/ai-openshell/sdk-go/openshell/v1/types" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/infrastructure/egress" "github.com/samcharles93/archie-core/internal/storage" ) @@ -23,9 +28,13 @@ import ( // other's. const instanceLabel = "archie.instance" -// agentCommand is the sandbox's main process. The image's own entrypoint is -// replaced by OpenShell's, so the agent is named here. -var agentCommand = []string{"archie-agent"} +// agentBinary is where the agent image installs archie-agent. The sandbox's +// main process names it, since OpenShell replaces the image's entrypoint, +// and policy admits archie's own services and model providers to it alone. +const agentBinary = "/usr/local/bin/archie-agent" + +// anyBinary admits every program in the sandbox to an endpoint. +const anyBinary = "/**" // writable are container paths tools write to inside the sandbox. They are // the container's own layer, so writing them exposes nothing on the host. @@ -47,28 +56,56 @@ type Options struct { // Poll is how often a running sandbox is checked for an exit; zero means // two seconds. Poll time.Duration - Log *slog.Logger + // ServicesHost is the DNS name a sandbox reaches NATS and the State Store + // by when they are addressed by IP or loopback. + ServicesHost string + Log *slog.Logger +} + +// Launch is one task's agent: what it runs, and everything it may reach. +type Launch struct { + Image string + Mounts []storage.Mount + // Env is the agent's environment apart from its network endpoints. + Env []string + // Worker is NATS and the State Store as the daemon reaches them, with the + // task's credentials. + Worker egress.Endpoints + // Providers are the gateway providers whose keys the agent's model calls + // carry, each to its own host. + Providers []Provider + // Hosts are further hosts, "host" or "host:port", any tool may reach. + Hosts []string +} + +// Provider is a credentialed gateway provider and the host its key goes to. +type Provider struct { + Gateway string + Host string + Port int } // Runtime creates, watches and removes task sandboxes on one gateway. type Runtime struct { - client v1.ClientInterface - workspace string - instance string - maxUptime func() time.Duration - poll time.Duration - log *slog.Logger + client v1.ClientInterface + workspace string + instance string + maxUptime func() time.Duration + poll time.Duration + servicesHost string + log *slog.Logger } // New returns a Runtime on client. func New(client v1.ClientInterface, opts Options) *Runtime { r := &Runtime{ - client: client, - workspace: opts.Workspace, - instance: opts.Instance, - maxUptime: opts.MaxUptime, - poll: opts.Poll, - log: opts.Log, + client: client, + workspace: opts.Workspace, + instance: opts.Instance, + maxUptime: opts.MaxUptime, + poll: opts.Poll, + servicesHost: opts.ServicesHost, + log: opts.Log, } if r.workspace == "" { r.workspace = "default" @@ -111,11 +148,11 @@ func (s *Sandbox) ExitDetail() string { } } -// Acquire creates a sandbox running the agent from image, with mounts bound -// in and env as its environment, and waits until it is ready. -func (r *Runtime) Acquire(ctx context.Context, image string, mounts []storage.Mount, env []string) (*Sandbox, error) { +// Acquire creates a sandbox running the agent l describes, and waits until it +// is ready. +func (r *Runtime) Acquire(ctx context.Context, l Launch) (*Sandbox, error) { name := fmt.Sprintf("%s-agent-%d", r.instance, time.Now().UnixNano()) - spec, err := r.spec(image, mounts, env) + spec, err := r.spec(l) if err != nil { return nil, err } @@ -174,8 +211,44 @@ func (r *Runtime) Sweep(ctx context.Context) error { return errors.Join(errs...) } -// spec is the sandbox a task runs in. -func (r *Runtime) spec(image string, mounts []storage.Mount, env []string) (*v1.SandboxSpec, error) { +// spec is the sandbox a task runs in: its environment, mounts and the network +// policy that is all it can reach. +func (r *Runtime) spec(l Launch) (*v1.SandboxSpec, error) { + nats, err := r.service(l.Worker.NATS) + if err != nil { + return nil, fmt.Errorf("nats: %w", err) + } + rules := map[string]v1.NetworkPolicyRule{"archie-nats": serviceRule("archie-nats", nats)} + var stateStore serviceAddr + if l.Worker.StateStore != "" { + if stateStore, err = r.service(l.Worker.StateStore); err != nil { + return nil, fmt.Errorf("state store: %w", err) + } + rules["archie-state-store"] = serviceRule("archie-state-store", stateStore) + } + for _, p := range l.Providers { + name := "model-" + p.Gateway + rules[name] = v1.NetworkPolicyRule{ + Name: name, + Endpoints: []v1.PolicyNetworkEndpoint{{ + Host: p.Host, Port: uint32(p.Port), Protocol: "rest", Access: v1.NetworkAccessPresetFull, //nolint:gosec // G115: a parsed port is 1 to 65535. + CredentialBinding: &types.NetworkCredentialBinding{Provider: p.Gateway}, + }}, + Binaries: []v1.PolicyNetworkBinary{{Path: agentBinary}}, + } + } + if len(l.Hosts) > 0 { + var endpoints []v1.PolicyNetworkEndpoint + for _, entry := range l.Hosts { + host, port, err := config.EgressHost(entry) + if err != nil { + return nil, err + } + endpoints = append(endpoints, v1.PolicyNetworkEndpoint{Host: host, Port: uint32(port)}) //nolint:gosec // G115: a parsed port is 1 to 65535. + } + rules["egress"] = v1.NetworkPolicyRule{Name: "egress", Endpoints: endpoints, Binaries: []v1.PolicyNetworkBinary{{Path: anyBinary}}} + } + env := append(slices.Clone(l.Env), egress.DirectWorkerEnv(nats.url, stateStore.url, l.Worker)...) environment := make(map[string]string, len(env)) for _, entry := range env { key, value, ok := strings.Cut(entry, "=") @@ -186,7 +259,7 @@ func (r *Runtime) spec(image string, mounts []storage.Mount, env []string) (*v1. } readWrite := slices.Clone(writable) var driverMounts []any - for _, m := range mounts { + for _, m := range l.Mounts { mount := map[string]any{"type": m.Type, "source": m.Source, "target": m.Destination, "read_only": m.ReadOnly} if m.Type == storage.MountTypeBind { // The same relabelling the Docker pool applies; Docker ignores @@ -203,18 +276,78 @@ func (r *Runtime) spec(image string, mounts []storage.Mount, env []string) (*v1. } return &v1.SandboxSpec{ Template: &v1.SandboxTemplate{ - Image: image, + Image: l.Image, Labels: map[string]string{instanceLabel: r.instance}, DriverConfig: map[string]any{"docker": map[string]any{"mounts": driverMounts}}, }, Environment: environment, - Command: slices.Clone(agentCommand), + Providers: providerNames(l.Providers), + Command: []string{agentBinary}, Policy: &v1.SandboxPolicy{ - Filesystem: &v1.FilesystemPolicy{IncludeWorkdir: true, ReadOnly: slices.Clone(readOnly), ReadWrite: readWrite}, + Filesystem: &v1.FilesystemPolicy{IncludeWorkdir: true, ReadOnly: slices.Clone(readOnly), ReadWrite: readWrite}, + NetworkPolicies: rules, }, }, nil } +func providerNames(providers []Provider) []string { + var names []string + for _, p := range providers { + names = append(names, p.Gateway) + } + return names +} + +// serviceAddr is one of archie's own services as a sandbox reaches it: the +// URL the agent dials, and the host and port policy admits. +type serviceAddr struct { + url string + host string + port int +} + +// service is target as a sandbox must address it. Policy admits TCP only to +// DNS names, and never to loopback, so a host given as an IP or as loopback +// is replaced by the configured services host on the same port. target is a +// URL ("nats://host:port"), a gRPC target ("dns:///host:port") or host:port. +func (r *Runtime) service(target string) (serviceAddr, error) { + prefix, hostport := "", strings.TrimSpace(target) + if i := strings.Index(hostport, "://"); i >= 0 { + prefix, hostport = hostport[:i+3], hostport[i+3:] + hostport = strings.TrimPrefix(hostport, "/") + } + if prefix == "dns://" { + prefix = "" + } + host, portText, err := net.SplitHostPort(hostport) + if err != nil { + return serviceAddr{}, fmt.Errorf("%q: want host:port", target) + } + port, err := strconv.Atoi(portText) + if err != nil || port < 1 || port > 65535 { + return serviceAddr{}, fmt.Errorf("%q: bad port", target) + } + if ip := net.ParseIP(host); ip != nil || strings.EqualFold(host, "localhost") { + if r.servicesHost == "" { + return serviceAddr{}, fmt.Errorf("%q is addressed by IP or loopback, which sandbox policy cannot admit; set the openshell services host", target) + } + host = r.servicesHost + } + hostport = net.JoinHostPort(host, strconv.Itoa(port)) + return serviceAddr{url: prefix + hostport, host: host, port: port}, nil +} + +// serviceRule admits the agent to one of archie's services over plain TCP. +// The sandbox leaves the stream alone: NATS speaks first, and the State Store +// client does its own TLS. +func serviceRule(name string, s serviceAddr) v1.NetworkPolicyRule { + return v1.NetworkPolicyRule{ + Name: name, + Endpoints: []v1.PolicyNetworkEndpoint{{Host: s.host, Port: uint32(s.port), Protocol: "tcp", TLS: v1.NetworkTLSModeSkip}}, //nolint:gosec // G115: a parsed port is 1 to 65535. + Binaries: []v1.PolicyNetworkBinary{{Path: agentBinary}}, + } +} + // watch closes s.exited once the sandbox stops running or outlives maxUptime. // A failed status read says nothing about the sandbox, so it never ends the // watch: a gateway hiccup must not abort a live run. diff --git a/internal/infrastructure/openshell/runtime_test.go b/internal/infrastructure/openshell/runtime_test.go index 46d432e57..7833436bd 100644 --- a/internal/infrastructure/openshell/runtime_test.go +++ b/internal/infrastructure/openshell/runtime_test.go @@ -9,6 +9,8 @@ import ( v1 "github.com/ai-openshell/sdk-go/openshell/v1" "github.com/ai-openshell/sdk-go/openshell/v1/fake" + + "github.com/samcharles93/archie-core/internal/infrastructure/egress" ) // TestTaskSandboxEndsWithItsTask guards the sandbox lifecycle: a task sees its @@ -33,7 +35,7 @@ func TestTaskSandboxEndsWithItsTask(t *testing.T) { defer client.Close() rt := New(client, Options{Instance: "archie", Poll: 5 * time.Millisecond, MaxUptime: func() time.Duration { return tt.maxUptime }}) - sb, err := rt.Acquire(t.Context(), "agent:test", nil, []string{"NATS_URL=nats://nats.example:4222"}) + sb, err := rt.Acquire(t.Context(), Launch{Image: "agent:test", Worker: egress.Endpoints{NATS: "nats://nats.example.internal:4222"}}) if err != nil { t.Fatal(err) }