Files
Reims-Go/internal/plugin/broker.go
T

312 lines
8.4 KiB
Go

package plugin
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
)
const maxPluginLogBytes = 2 << 20 // 2 MiB log rotation threshold (§6.1)
// ManagedProcess represents a host-spawned VM process requested by an L3 driver
// so the VM process lives OUTSIDE the Sidecar's Job Object (§5.3).
type ManagedProcess struct {
PID int
PluginID string
VMName string
cmd *exec.Cmd
done chan struct{}
}
// Broker mediates all Host API calls from plugins (L3 Sidecar, L4 iframe bridge):
// permission checking, sensitive field redaction, per-plugin rate limiting,
// rotating audit log, and host-managed process launching (§3.1, §5.3, §7).
type Broker struct {
mu sync.Mutex
layout PluginsLayout
reg *Registry
redactFn func(string) string
// Rate limiting: sliding window counter per plugin.
rates map[string]*rateWindow
// Managed VM processes spawned on behalf of drivers (decoupled from Sidecar Job Object).
procs map[int]*ManagedProcess
onNotify func(pluginID, title, body string)
}
type rateWindow struct {
windowStart time.Time
count int
}
func NewBroker(layout PluginsLayout, reg *Registry, redactFn func(string) string) *Broker {
if redactFn == nil {
redactFn = func(s string) string { return s }
}
return &Broker{
layout: layout,
reg: reg,
redactFn: redactFn,
rates: make(map[string]*rateWindow),
procs: make(map[int]*ManagedProcess),
}
}
func (b *Broker) SetNotifier(fn func(pluginID, title, body string)) {
b.mu.Lock()
b.onNotify = fn
b.mu.Unlock()
}
// Authorize verifies that pluginID is active, holds perm (and has approved it
// when medium/high risk), and is within its rate limit (§7.1, §7.3).
func (b *Broker) Authorize(pluginID, perm string) error {
if ClassifyPermission(perm) == PermForbidden {
b.Audit(pluginID, "DENY", fmt.Sprintf("forbidden permission %q", perm))
return fmt.Errorf("permission %q does not exist or is forbidden", perm)
}
if b.reg == nil {
return errors.New("registry unavailable")
}
info, ok := b.reg.Info(pluginID)
if !ok {
return fmt.Errorf("unknown plugin %q", pluginID)
}
if info.State != StateActive && info.State != StateDegraded {
return fmt.Errorf("plugin %q is not active (state=%s)", pluginID, info.State)
}
if info.NeedsApproval {
b.Audit(pluginID, "DENY", fmt.Sprintf("unapproved plugin attempted %q", perm))
return fmt.Errorf("plugin %q requires high-risk permission approval", pluginID)
}
declared := false
for _, p := range info.Permissions {
if p.Name == perm {
declared = true
break
}
}
if !declared {
b.Audit(pluginID, "DENY", fmt.Sprintf("undeclared permission %q", perm))
return fmt.Errorf("plugin %q lacks permission %q", pluginID, perm)
}
if ClassifyPermission(perm) == PermHigh && info.Trust != TrustOfficial && info.Source != SourceBuiltin {
approved := false
for _, ap := range info.ApprovedPermissions {
if ap == perm {
approved = true
break
}
}
if !approved {
b.Audit(pluginID, "DENY", fmt.Sprintf("unapproved high-risk permission %q", perm))
return fmt.Errorf("plugin %q has not approved high-risk permission %q", pluginID, perm)
}
}
// Rate limit: max 120 Host API calls / second per plugin.
if !b.allowRate(pluginID, 120) {
b.Audit(pluginID, "RATE_LIMIT", perm)
return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID)
}
return nil
}
func (b *Broker) allowRate(pluginID string, limitPerSec int) bool {
b.mu.Lock()
defer b.mu.Unlock()
now := time.Now()
rw := b.rates[pluginID]
if rw == nil || now.Sub(rw.windowStart) >= time.Second {
b.rates[pluginID] = &rateWindow{windowStart: now, count: 1}
return true
}
if rw.count >= limitPerSec {
return false
}
rw.count++
return true
}
// Audit appends a redacted audit or stderr line to `<DataRoot>/plugins/logs/<id>.log`
// with automatic rotation at 2 MiB (§6.1).
func (b *Broker) Audit(pluginID, tag, msg string) {
if b == nil || b.layout.Root == "" || pluginID == "" {
return
}
if strings.ContainsAny(pluginID, `/\`) || strings.Contains(pluginID, "..") {
return
}
trimmed := strings.TrimSpace(msg)
if len(trimmed) > 4096 {
trimmed = trimmed[:4096] + "…"
}
safeMsg := b.redactFn(trimmed)
line := fmt.Sprintf("%s [%s] %s\n", time.Now().UTC().Format(time.RFC3339), tag, safeMsg)
b.mu.Lock()
defer b.mu.Unlock()
if err := os.MkdirAll(b.layout.LogsDir(), 0o755); err != nil {
return
}
logPath := b.layout.LogPath(pluginID)
if info, err := os.Stat(logPath); err == nil && info.Size() >= maxPluginLogBytes {
_ = os.Rename(logPath, logPath+".1")
}
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return
}
_, _ = f.WriteString(line)
_ = f.Close()
}
// StripSensitiveFields returns a copy of m with forbidden/sensitive keys removed (§1.2, §7.1).
func StripSensitiveFields(m map[string]any) map[string]any {
if m == nil {
return nil
}
blocked := map[string]bool{
"serial": true, "serial_number": true, "mlb": true, "uuid": true,
"rom": true, "mac": true, "mac_address": true, "osk": true,
"token": true, "bearer": true,
}
out := make(map[string]any, len(m))
for k, v := range m {
if blocked[strings.ToLower(k)] {
continue
}
if sub, ok := v.(map[string]any); ok {
out[k] = StripSensitiveFields(sub)
} else {
out[k] = v
}
}
return out
}
// Notify emits a host notification on behalf of a plugin with `ui:notify`.
func (b *Broker) Notify(pluginID, title, body string) error {
if err := b.Authorize(pluginID, "ui:notify"); err != nil {
return err
}
b.Audit(pluginID, "NOTIFY", title+": "+body)
b.mu.Lock()
fn := b.onNotify
b.mu.Unlock()
if fn != nil {
fn(pluginID, b.redactFn(title), b.redactFn(body))
}
return nil
}
// SpawnManagedVMProcess spawns an external VM executable (e.g. qemu-system-x86_64)
// owned by the HOST rather than the Sidecar's Job Object, so Sidecar crashes or
// restarts never kill running VMs (§5.3).
func (b *Broker) SpawnManagedVMProcess(ctx context.Context, pluginID, vmName, exePath string, args []string, workDir string, env []string) (int, error) {
if err := b.Authorize(pluginID, "process:spawn"); err != nil {
return 0, err
}
if err := ctx.Err(); err != nil {
return 0, err
}
if strings.TrimSpace(exePath) == "" {
return 0, errors.New("executable path required")
}
// Ensure executable path exists and is a regular file.
st, err := os.Stat(exePath)
if err != nil {
return 0, fmt.Errorf("executable not found: %w", err)
}
if st.IsDir() {
return 0, errors.New("executable path must be a file, not a directory")
}
cmd := exec.Command(exePath, args...)
if workDir != "" {
cmd.Dir = workDir
}
if len(env) > 0 {
cmd.Env = append(os.Environ(), env...)
}
configureDetachedVMProcess(cmd)
if err := cmd.Start(); err != nil {
b.Audit(pluginID, "SPAWN_ERR", fmt.Sprintf("vm=%s exe=%s err=%v", vmName, filepath.Base(exePath), err))
return 0, err
}
pid := cmd.Process.Pid
mp := &ManagedProcess{
PID: pid,
PluginID: pluginID,
VMName: vmName,
cmd: cmd,
done: make(chan struct{}),
}
b.mu.Lock()
b.procs[pid] = mp
b.mu.Unlock()
b.Audit(pluginID, "SPAWN", fmt.Sprintf("vm=%s pid=%d exe=%s", vmName, pid, filepath.Base(exePath)))
go func() {
_ = cmd.Wait()
close(mp.done)
b.mu.Lock()
delete(b.procs, pid)
b.mu.Unlock()
b.Audit(pluginID, "EXIT", fmt.Sprintf("vm=%s pid=%d", vmName, pid))
}()
return pid, nil
}
// StopManagedVMProcess terminates a host-managed VM process by PID.
func (b *Broker) StopManagedVMProcess(pluginID string, pid int) error {
if err := b.Authorize(pluginID, "vm:control"); err != nil {
return err
}
b.mu.Lock()
mp := b.procs[pid]
b.mu.Unlock()
if mp == nil || mp.cmd == nil || mp.cmd.Process == nil {
return nil
}
if mp.PluginID != pluginID {
return fmt.Errorf("PID %d is not owned by plugin %q", pid, pluginID)
}
return mp.cmd.Process.Kill()
}
// IsManagedProcessRunning reports whether pid is still alive in the broker.
func (b *Broker) IsManagedProcessRunning(pid int) bool {
b.mu.Lock()
mp := b.procs[pid]
b.mu.Unlock()
if mp == nil {
return false
}
select {
case <-mp.done:
return false
default:
return true
}
}
// IsManagedProcessRunningForPlugin reports whether pid is owned by pluginID and alive.
func (b *Broker) IsManagedProcessRunningForPlugin(pluginID string, pid int) bool {
b.mu.Lock()
mp := b.procs[pid]
b.mu.Unlock()
if mp == nil || mp.PluginID != pluginID {
return false
}
select {
case <-mp.done:
return false
default:
return true
}
}