package host import ( "context" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/hex" "errors" "fmt" "net" "os" "path/filepath" "strings" "github.com/hashicorp/go-hclog" goplugin "github.com/hashicorp/go-plugin" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" ) // Runtime starts one extension. The host tries its runtimes in order and // refuses to start an extension when none of them can serve it, so an // environment with neither local confinement nor a remote endpoint runs no // extension at all. type Runtime interface { // Name identifies the runtime in a refusal. Name() string // Available reports why this runtime cannot serve spec, or nil when it can. Available(spec Spec) error // Start runs, or dials, the extension serving surface and returns the // dispensed client with the state that keeps it running. A runtime that // fails leaves nothing running. Start(ctx context.Context, spec Spec, surface string, impl goplugin.Plugin) (any, *proc, error) } // RemoteTLS holds the mutual-TLS material used to authenticate remote extension // gRPC endpoints. type RemoteTLS struct { CAFile string `toml:"ca_file"` CertFile string `toml:"cert_file"` KeyFile string `toml:"key_file"` } // RemoteEndpoint names a pre-deployed gRPC extension service (sidecar socket // or mTLS pod address). type RemoteEndpoint struct { Address string `toml:"address"` ServerName string `toml:"server_name"` } // RemoteConfig controls remote gRPC extension routing. type RemoteConfig struct { RequireRemote bool TLS RemoteTLS Endpoints map[string]RemoteEndpoint } // RemoteGRPCRuntime dials an extension that runs outside this process: a // sidecar socket or a dedicated pod reached over mTLS. It is the runtime a // Kubernetes cluster uses, where restricted Pod Security Standards forbid the // namespaces LocalNamespaceRuntime needs and NetworkPolicy admits only the // endpoint. type RemoteGRPCRuntime struct { tls *tls.Config endpoints map[string]RemoteEndpoint } func (RemoteGRPCRuntime) Name() string { return "remote gRPC" } func (r RemoteGRPCRuntime) Available(spec Spec) error { ep, ok := r.endpoint(spec) if !ok { return errors.New("no endpoint is configured") } if r.tls == nil && !strings.HasPrefix(ep.Address, "unix://") { return fmt.Errorf("endpoint %s needs mTLS credentials", ep.Address) } return nil } func (r RemoteGRPCRuntime) Start(ctx context.Context, spec Spec, _ string, impl goplugin.Plugin) (any, *proc, error) { ep, ok := r.endpoint(spec) if !ok { return nil, nil, errors.New("no endpoint is configured") } gp, ok := impl.(goplugin.GRPCPlugin) if !ok { return nil, nil, errors.New("plugin does not support gRPC") } conn, err := dialRemote(ep, r.tls) if err != nil { return nil, nil, fmt.Errorf("dial %s: %w", ep.Address, err) } raw, err := gp.GRPCClient(ctx, nil, conn) if err != nil { _ = conn.Close() return nil, nil, fmt.Errorf("client: %w", err) } return raw, &proc{conn: conn}, nil } // endpoint finds the endpoint the operator mapped to spec, by installation ID // before name. func (r RemoteGRPCRuntime) endpoint(spec Spec) (RemoteEndpoint, bool) { if spec.Key != "" { if ep, ok := r.endpoints[spec.Key]; ok { return ep, true } } if spec.Name != "" { if ep, ok := r.endpoints[spec.Name]; ok { return ep, true } } return RemoteEndpoint{}, false } // LocalNamespaceRuntime runs an extension as a local subprocess in its own user // and network namespace, which holds nothing but a relay to the egress gate. It // is the Compose and VM runtime; where the kernel or the container runtime // refuses those namespaces, an operator configures remote endpoints instead. type LocalNamespaceRuntime struct { hclog hclog.Logger // disabled is set when the operator requires remote endpoints, so no // extension runs as a subprocess of this process. disabled bool } func (LocalNamespaceRuntime) Name() string { return "local namespace" } func (r LocalNamespaceRuntime) Available(spec Spec) error { if r.disabled { return errors.New("local subprocess execution is disabled") } if len(spec.Egress) == 0 { // Nothing to project into a namespace: this package runs on the host's // network either way. return nil } return namespacesAvailable() } func (r LocalNamespaceRuntime) Start(ctx context.Context, spec Spec, surface string, impl goplugin.Plugin) (any, *proc, error) { sum, err := hex.DecodeString(spec.SHA256) if err != nil || len(sum) != sha256.Size { return nil, nil, errors.New("sha256 must be a hex digest") } // The verified file is what runs: the confined launcher execs this open // descriptor, so swapping the path after the check changes nothing. binary, err := openVerified(spec.Path, sum) if err != nil { return nil, nil, err } defer func() { _ = binary.Close() }() cmd, g, err := command(ctx, binary, spec.Egress) if err != nil { return nil, nil, err } cmd.Env = passEnv(spec.Env) p := &proc{gate: g, client: goplugin.NewClient(&goplugin.ClientConfig{ HandshakeConfig: Handshake, Plugins: goplugin.PluginSet{surface: impl}, Cmd: cmd, AllowedProtocols: []goplugin.Protocol{goplugin.ProtocolGRPC}, SkipHostEnv: true, AutoMTLS: true, Logger: r.hclog.Named(spec.Name), })} rpc, err := p.client.Client() if err != nil { p.kill() return nil, nil, fmt.Errorf("connect: %w", err) } raw, err := rpc.Dispense(surface) if err != nil { p.kill() return nil, nil, fmt.Errorf("dispense %s: %w", surface, err) } return raw, p, nil } func validateRemoteConfig(cfg RemoteConfig) (*tls.Config, map[string]RemoteEndpoint, error) { endpoints := make(map[string]RemoteEndpoint, len(cfg.Endpoints)) needTLS := false for k, ep := range cfg.Endpoints { key := strings.TrimSpace(k) addr := strings.TrimSpace(ep.Address) if key == "" || addr == "" { return nil, nil, fmt.Errorf("remote endpoint %q: address is required", k) } if strings.HasPrefix(addr, "unix://") { if err := checkUnixAddress(addr); err != nil { return nil, nil, fmt.Errorf("remote endpoint %q: %w", key, err) } } else { if _, _, err := net.SplitHostPort(addr); err != nil { return nil, nil, fmt.Errorf("remote endpoint %q: address must be host:port or unix://path: %w", key, err) } needTLS = true } endpoints[key] = RemoteEndpoint{Address: addr, ServerName: strings.TrimSpace(ep.ServerName)} } var tlsCfg *tls.Config hasAnyTLS := cfg.TLS.CAFile != "" || cfg.TLS.CertFile != "" || cfg.TLS.KeyFile != "" if needTLS || hasAnyTLS { var err error tlsCfg, err = loadRemoteTLS(cfg.TLS) if err != nil { return nil, nil, err } } return tlsCfg, endpoints, nil } func checkUnixAddress(addr string) error { sock := strings.TrimPrefix(addr, "unix://") if !strings.HasPrefix(sock, "/") { return errors.New("unix socket path must be absolute") } clean := filepath.Clean(sock) if clean != sock { return fmt.Errorf("unix socket path %q must be clean", sock) } return nil } func loadRemoteTLS(cfg RemoteTLS) (*tls.Config, error) { if cfg.CAFile == "" || cfg.CertFile == "" || cfg.KeyFile == "" { return nil, errors.New("remote mTLS requires ca_file, cert_file, and key_file") } caPEM, err := os.ReadFile(cfg.CAFile) //nolint:gosec // operator-configured CA path if err != nil { return nil, fmt.Errorf("read remote CA %s: %w", cfg.CAFile, err) } pool := x509.NewCertPool() if !pool.AppendCertsFromPEM(caPEM) { return nil, fmt.Errorf("parse remote CA %s: no certificates found", cfg.CAFile) } cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile) if err != nil { return nil, fmt.Errorf("load remote client keypair: %w", err) } return &tls.Config{ RootCAs: pool, Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13, }, nil } func dialRemote(ep RemoteEndpoint, baseTLS *tls.Config) (*grpc.ClientConn, error) { if strings.HasPrefix(ep.Address, "unix://") { creds := insecure.NewCredentials() if baseTLS != nil && ep.ServerName != "" { cfg := baseTLS.Clone() cfg.ServerName = ep.ServerName creds = credentials.NewTLS(cfg) } return grpc.NewClient("unix://"+strings.TrimPrefix(ep.Address, "unix://"), grpc.WithTransportCredentials(creds)) } if baseTLS == nil { return nil, fmt.Errorf("remote endpoint %q requires mTLS credentials", ep.Address) } cfg := baseTLS.Clone() if ep.ServerName != "" { cfg.ServerName = ep.ServerName } else if host, _, err := net.SplitHostPort(ep.Address); err == nil { cfg.ServerName = host } return grpc.NewClient(ep.Address, grpc.WithTransportCredentials(credentials.NewTLS(cfg))) }