Files
archie/modules/connectors/internal/host/confine_linux.go
T
sam cf249d7643 feat(connectors): MCP servers as a fourth accepted package, with their declared tools offered to agents (archie #2005)
An investigation needs Prometheus's own metrics, and Prometheus publishes an
MCP server, so the connectors module now runs MCP servers as published instead
of wrapping them: a stdio binary in its own user and network namespace with an
egress allow-list, or an HTTP endpoint dialled through declared egress.

Acceptance names the transport, the tools it permits, and the credential slots
that resolve into the server's environment (stdio) or Authorization header
(HTTP). Each permitted tool is declared as a lookup, or as an action with its
effect; a tool the server lists but the acceptance doesn't name is never
offered, and a declared tool the server doesn't list fails the start rather
than going silently missing. Declared tools reach agents beside connector
lookups through the same declaration and the same call path, with the server's
own input schema, under a name no connector can take: an accepted name runs one
package.

A server that fails to start, exits or stops answering is reported by readiness
and reconnected with backoff. Tool calls carry a deadline, results are capped,
and an error result fails its call with the server's own text rather than the
run.

The investigate prompt now asks for a time-until-full figure from
`predict_linear` through the metrics server instead of an estimate from raw
points.

The old core MCP path stays for now: the legacy gateway and task containers
still read config.Tools.MCPServers, so it goes with them.
2026-11-15 23:43:39 +11:00

174 lines
5.5 KiB
Go

package host
import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"os/signal"
"runtime"
"syscall"
"golang.org/x/sys/unix"
)
// launcherArg makes any binary importing this package the confined
// launcher: the extension's parent inside its network namespace.
const launcherArg = "__extension-egress"
// proxyAddr is where the launcher serves the extension's only way out.
const proxyAddr = "127.0.0.1:3128"
func init() {
if len(os.Args) > 2 && os.Args[1] == launcherArg {
os.Exit(launch(os.Args[2], os.Args[3:]))
}
}
// confinedCommand re-execs this binary as the launcher in a fresh user and
// network namespace. The namespace holds only loopback, so the child cannot
// reach anything except through the launcher's relay to socket. Where the
// kernel refuses the namespaces, the start fails: there is no unconfined
// fallback. args reach the child as they were given to it.
//
// The process lives until ctx ends, which is the session's lifetime rather
// than any one call's deadline; Pdeathsig ends it if this process dies.
func confinedCommand(ctx context.Context, binary *os.File, args []string, socket string) (*exec.Cmd, error) {
self, err := os.Executable()
if err != nil {
return nil, err
}
uid, gid := os.Getuid(), os.Getgid()
launchArgs := append([]string{launcherArg, socket}, args...)
//nolint:gosec // the binary is this one, named by path; the arguments are the accepted package's own.
cmd := exec.CommandContext(ctx, self, launchArgs...)
cmd.ExtraFiles = []*os.File{binary}
cmd.SysProcAttr = &syscall.SysProcAttr{
Cloneflags: syscall.CLONE_NEWUSER | syscall.CLONE_NEWNET,
UidMappings: []syscall.SysProcIDMap{{ContainerID: uid, HostID: uid, Size: 1}},
GidMappings: []syscall.SysProcIDMap{{ContainerID: gid, HostID: gid, Size: 1}},
// Only the launcher holds this, to bring loopback up; it clears it
// before the extension starts.
AmbientCaps: []uintptr{unix.CAP_NET_ADMIN},
Pdeathsig: syscall.SIGKILL,
}
return cmd, nil
}
// openCommand runs the verified binary by its open descriptor with the host's
// network, for a package that declares no egress hosts.
func openCommand(ctx context.Context, binary *os.File) *exec.Cmd {
path := fmt.Sprintf("/proc/%d/fd/%d", os.Getpid(), binary.Fd())
cmd := exec.CommandContext(ctx, path) // the host-verified binary, by descriptor
cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
return cmd
}
// launch runs inside the namespace: loopback up, relay listening, then the
// child from descriptor 3 with every capability gone.
func launch(socket string, args []string) int {
ctx := context.Background()
if err := loopbackUp(); err != nil {
fmt.Fprintln(os.Stderr, "extension egress: loopback:", err)
return 1
}
ln, err := (&net.ListenConfig{}).Listen(ctx, "tcp", proxyAddr)
if err != nil {
fmt.Fprintln(os.Stderr, "extension egress: relay:", err)
return 1
}
go relay(ctx, ln, socket)
if err := unix.Prctl(unix.PR_CAP_AMBIENT, unix.PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0); err != nil {
fmt.Fprintln(os.Stderr, "extension egress: drop capabilities:", err)
return 1
}
if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil {
fmt.Fprintln(os.Stderr, "extension egress: no_new_privs:", err)
return 1
}
syscall.CloseOnExec(3)
return runExtension(ctx, fmt.Sprintf("/proc/%d/fd/3", os.Getpid()), args)
}
// runExtension starts the child from path and mirrors its exit. Pdeathsig ties
// the child to this thread, so killing the launcher kills it.
func runExtension(ctx context.Context, path string, args []string) int {
runtime.LockOSThread()
proxy := "http://" + proxyAddr
//nolint:gosec // the binary is named by its verified descriptor; the arguments are the accepted package's own.
cmd := exec.CommandContext(ctx, path, args...) // the host-verified binary, by descriptor
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
cmd.Env = append(os.Environ(),
"HTTP_PROXY="+proxy, "HTTPS_PROXY="+proxy, "ALL_PROXY="+proxy,
"http_proxy="+proxy, "https_proxy="+proxy, "all_proxy="+proxy, "NO_PROXY=", "no_proxy=")
cmd.SysProcAttr = &syscall.SysProcAttr{Pdeathsig: syscall.SIGKILL}
if err := cmd.Start(); err != nil {
fmt.Fprintln(os.Stderr, "extension egress: start:", err)
return 1
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
go func() {
for s := range signals {
_ = cmd.Process.Signal(s)
}
}()
err := cmd.Wait()
if exit, ok := errors.AsType[*exec.ExitError](err); ok {
return exit.ExitCode()
}
if err != nil {
return 1
}
return 0
}
func loopbackUp() error {
fd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM|unix.SOCK_CLOEXEC, 0)
if err != nil {
return err
}
defer func() { _ = unix.Close(fd) }()
ifr, err := unix.NewIfreq("lo")
if err != nil {
return err
}
if err := unix.IoctlIfreq(fd, unix.SIOCGIFFLAGS, ifr); err != nil {
return err
}
ifr.SetUint16(ifr.Uint16() | unix.IFF_UP)
return unix.IoctlIfreq(fd, unix.SIOCSIFFLAGS, ifr)
}
// relay carries each proxy connection to the host's gate socket.
func relay(ctx context.Context, ln net.Listener, socket string) {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func() {
defer func() { _ = conn.Close() }()
upstream, err := (&net.Dialer{}).DialContext(ctx, "unix", socket)
if err != nil {
return
}
defer func() { _ = upstream.Close() }()
go func() {
_, _ = io.Copy(upstream, conn)
closeWrite(upstream)
}()
_, _ = io.Copy(conn, upstream)
}()
}
}
func closeWrite(c net.Conn) {
if cw, ok := c.(interface{ CloseWrite() error }); ok {
_ = cw.CloseWrite()
}
}