Files
archie/modules/connectors/internal/host/host.go
T

283 lines
7.8 KiB
Go

// Package host supervises extension plugins: one go-plugin subprocess per
// enabled extension, each serving a gRPC surface from proto/<surface>/v1.
package host
import (
"bytes"
"cmp"
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"sync"
"github.com/hashicorp/go-hclog"
goplugin "github.com/hashicorp/go-plugin"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
)
// Handshake is shared by the host and every extension binary. Bump
// ProtocolVersion on an incompatible change to the handshake itself; each
// surface versions its own proto package.
var Handshake = goplugin.HandshakeConfig{
ProtocolVersion: 1,
MagicCookieKey: "ARCHIE_EXTENSION",
MagicCookieValue: "archie",
}
// Spec is one extension to run.
type Spec struct {
Name string
// Key identifies the running process: Start, Stop and Alive use it. It is
// the installation ID, so two installations of one package run apart. It
// defaults to Name.
Key string
// Path is the extension binary.
Path string
// SHA256 is the hex digest the binary must match before it is launched.
SHA256 string
// Env names the host environment variables the extension may see. PATH and
// HOME are always passed so a plugin can find the CLI it wraps.
Env []string
// Egress lists the hosts the extension may reach through its proxy.
Egress []string
}
// Host owns the running extension processes, keyed by Spec.Key.
type Host struct {
// log is the service's logger; plugin lifecycle goes through hclog.
log *slog.Logger
hclog hclog.Logger
mu sync.Mutex
procs map[string]*proc
requireRemote bool
remoteTLS *tls.Config
remotes map[string]RemoteEndpoint
}
// proc is one running extension: either a local go-plugin subprocess and its
// egress gate, or a remote gRPC client connection.
type proc struct {
client *goplugin.Client
gate *gate
conn *grpc.ClientConn
}
func (p *proc) kill() {
if p.conn != nil {
_ = p.conn.Close()
}
if p.client != nil {
p.client.Kill()
}
if p.gate != nil {
p.gate.close()
}
}
func (p *proc) alive() bool {
if p.conn != nil {
return p.conn.GetState() != connectivity.Shutdown
}
return p.client != nil && !p.client.Exited()
}
func command(ctx context.Context, binary *os.File, egress []string) (*exec.Cmd, *gate, error) {
if len(egress) == 0 {
// Nothing to allow, so there is no relay to reach through: confining
// this would give it loopback and a proxy address that nothing serves.
return openCommand(ctx, binary, nil), nil, nil
}
g, err := openGate(ctx, egress)
if err != nil {
return nil, nil, fmt.Errorf("egress: %w", err)
}
cmd, err := confinedCommand(ctx, binary, nil, g.socket)
if err != nil {
g.close()
return nil, nil, err
}
return cmd, g, nil
}
// NewHost returns a Host that reports plugin lifecycle problems to log.
func NewHost(log *slog.Logger) *Host {
return &Host{log: log, hclog: newSlogger(log), procs: make(map[string]*proc)}
}
// UseRemotes configures static remote gRPC+mTLS extension endpoints for
// hardened Kubernetes clusters where local namespace confinement is disabled.
func (h *Host) UseRemotes(cfg RemoteConfig) error {
tlsCfg, endpoints, err := validateRemoteConfig(cfg)
if err != nil {
return err
}
h.mu.Lock()
h.requireRemote = cfg.RequireRemote
h.remoteTLS = tlsCfg
h.remotes = cloneEndpoints(endpoints)
h.mu.Unlock()
return nil
}
// Start launches spec serving surface and returns the dispensed client. An
// extension already running under the same name is stopped first, so Start is
// also how a changed binary or setting takes effect.
func (h *Host) Start(ctx context.Context, spec Spec, surface string, impl goplugin.Plugin) (any, error) {
if ep, ok := h.lookupRemote(spec); ok {
return h.startRemote(ctx, spec, ep, impl)
}
h.mu.Lock()
requireRemote := h.requireRemote
h.mu.Unlock()
if requireRemote {
return nil, fmt.Errorf("extension %q: local subprocess execution is disabled and no remote endpoint is configured", spec.Name)
}
return h.startLocal(ctx, spec, surface, impl)
}
func (h *Host) startRemote(ctx context.Context, spec Spec, ep RemoteEndpoint, impl goplugin.Plugin) (any, error) {
gp, ok := impl.(goplugin.GRPCPlugin)
if !ok {
return nil, fmt.Errorf("extension %q: plugin does not support gRPC", spec.Name)
}
h.mu.Lock()
baseTLS := h.remoteTLS
h.mu.Unlock()
conn, err := dialRemote(ep, baseTLS)
if err != nil {
return nil, fmt.Errorf("extension %q: dial remote %s: %w", spec.Name, ep.Address, err)
}
raw, err := gp.GRPCClient(ctx, nil, conn)
if err != nil {
_ = conn.Close()
return nil, fmt.Errorf("extension %q: remote client: %w", spec.Name, err)
}
h.replaceProc(cmp.Or(spec.Key, spec.Name), &proc{conn: conn})
return raw, nil
}
func (h *Host) startLocal(ctx context.Context, spec Spec, surface string, impl goplugin.Plugin) (any, error) {
sum, err := hex.DecodeString(spec.SHA256)
if err != nil || len(sum) != sha256.Size {
return nil, fmt.Errorf("extension %q: sha256 must be a hex digest", spec.Name)
}
// 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, fmt.Errorf("extension %q: %w", spec.Name, err)
}
defer func() { _ = binary.Close() }()
cmd, g, err := command(ctx, binary, spec.Egress)
if err != nil {
return nil, fmt.Errorf("extension %q: %w", spec.Name, 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: h.hclog.Named(spec.Name),
})}
rpc, err := p.client.Client()
if err != nil {
p.kill()
return nil, fmt.Errorf("extension %q: connect: %w", spec.Name, err)
}
raw, err := rpc.Dispense(surface)
if err != nil {
p.kill()
return nil, fmt.Errorf("extension %q: dispense %s: %w", spec.Name, surface, err)
}
h.replaceProc(cmp.Or(spec.Key, spec.Name), p)
return raw, nil
}
func (h *Host) replaceProc(key string, next *proc) {
h.mu.Lock()
old := h.procs[key]
h.procs[key] = next
h.mu.Unlock()
if old != nil {
old.kill()
}
}
// Stop kills the named extension. Stopping one that is not running is not an
// error.
func (h *Host) Stop(name string) {
h.mu.Lock()
p := h.procs[name]
delete(h.procs, name)
h.mu.Unlock()
if p != nil {
p.kill()
}
}
// Alive reports whether the named extension's process or remote connection is
// active.
func (h *Host) Alive(name string) bool {
h.mu.Lock()
defer h.mu.Unlock()
p := h.procs[name]
return p != nil && p.alive()
}
// Close stops every extension.
func (h *Host) Close() {
h.mu.Lock()
procs := h.procs
h.procs = make(map[string]*proc)
h.mu.Unlock()
for _, p := range procs {
p.kill()
}
}
// openVerified opens the extension binary and checks it against sum.
func openVerified(path string, sum []byte) (*os.File, error) {
f, err := os.Open(path) // the path is the installed package's binary
if err != nil {
return nil, err
}
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
_ = f.Close()
return nil, err
}
if !bytes.Equal(h.Sum(nil), sum) {
_ = f.Close()
return nil, errors.New("binary does not match its checksum")
}
return f, nil
}
func passEnv(names []string) []string {
defaults := []string{"PATH", "HOME", "SSL_CERT_FILE", "SSL_CERT_DIR"}
env := make([]string, 0, len(names)+len(defaults))
seen := make(map[string]struct{}, len(names)+len(defaults))
for _, name := range append(defaults, names...) {
if _, dup := seen[name]; dup {
continue
}
seen[name] = struct{}{}
if value, ok := os.LookupEnv(name); ok {
env = append(env, name+"="+value)
}
}
return env
}