package plugin import ( "context" "errors" "fmt" "net" "net/url" "os" "os/exec" "path/filepath" "strings" "sync" "time" "github.com/Nwflower/reims-go/internal/plugin/sidecarproc" ) 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). The process // and every child it starts belong to one per-VM job. type ManagedProcess struct { PID int PluginID string VMName string // DriverID is empty only for legacy spawns that named no driver. DriverID string cmd *exec.Cmd job *sidecarproc.VMJob 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 procsByRef map[string]*ManagedProcess // VMs being spawned right now, so two requests cannot both start one. spawning map[string]bool onNotify func(pluginID, title, body string) onLog func(source, line string) onVMExit func(driverID, vmName string) onVMState func(pluginID string, rep ReportedVMState) error } 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), procsByRef: make(map[string]*ManagedProcess), } } func (b *Broker) SetNotifier(fn func(pluginID, title, body string)) { b.mu.Lock() b.onNotify = fn b.mu.Unlock() } // SetLogger registers the app log that Audit also writes to. Call it before any // plugin starts. func (b *Broker) SetLogger(fn func(source, line string)) { b.onLog = fn } // SetVMExitHandler registers a callback fired once the last process of a // driver-spawned VM has exited (not merely its launcher). func (b *Broker) SetVMExitHandler(fn func(driverID, vmName string)) { b.mu.Lock() b.onVMExit = fn b.mu.Unlock() } // SetVMStateHandler registers the receiver of `host/vm.reportState`. func (b *Broker) SetVMStateHandler(fn func(pluginID string, rep ReportedVMState) error) { b.mu.Lock() b.onVMState = fn b.mu.Unlock() } // ResolveRefDriver returns the driver a plugin may act for: driverID when the // plugin declares it, the plugin's only driver when driverID is empty. func (b *Broker) ResolveRefDriver(pluginID, driverID string) (string, error) { return b.resolveRefDriver(pluginID, driverID) } // IsLoopbackHost reports whether host names this machine's loopback. func IsLoopbackHost(host string) bool { host = strings.ToLower(strings.TrimSpace(host)) if host == "localhost" { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } func defaultPort(scheme string) string { if scheme == "http" { return "80" } return "443" } // netPermissionMatches reports whether a declared `net:` permission covers u. // The permission is either a full origin (`net:https://host[:port]`) or a bare // host (`net:host`, `net:host:port`). func netPermissionMatches(permission string, u *url.URL) bool { spec, ok := strings.CutPrefix(strings.TrimSpace(permission), "net:") if !ok || strings.TrimSpace(spec) == "" { return false } spec = strings.ToLower(strings.TrimSpace(spec)) host := strings.ToLower(u.Hostname()) port := u.Port() if port == "" { port = defaultPort(u.Scheme) } if strings.Contains(spec, "://") { origin, err := url.Parse(spec) if err != nil || origin.Hostname() == "" || origin.Path != "" && origin.Path != "/" { return false } oPort := origin.Port() if oPort == "" { oPort = defaultPort(origin.Scheme) } return origin.Scheme == u.Scheme && strings.EqualFold(origin.Hostname(), host) && oPort == port } if h, p, err := net.SplitHostPort(spec); err == nil { return strings.EqualFold(h, host) && p == port } return spec == host } // AuthorizeNetOrigin checks that pluginID is active and may reach rawURL: the // URL must name a `net:` origin the plugin declared, use HTTPS (plain HTTP is // allowed for loopback only) and carry no user info. func (b *Broker) AuthorizeNetOrigin(pluginID, rawURL string) error { u, err := url.Parse(strings.TrimSpace(rawURL)) if err != nil || u.Host == "" || u.Hostname() == "" { return fmt.Errorf("invalid URL %q", rawURL) } if u.User != nil { b.Audit(pluginID, "DENY", "URL with user info") return errors.New("URLs with user info are not allowed") } switch u.Scheme { case "https": case "http": if !IsLoopbackHost(u.Hostname()) { b.Audit(pluginID, "DENY", "plain HTTP to "+u.Hostname()) return fmt.Errorf("plain HTTP is only allowed for loopback hosts, not %q", u.Hostname()) } default: return fmt.Errorf("unsupported URL scheme %q", u.Scheme) } 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 { return fmt.Errorf("plugin %q requires permission approval", pluginID) } for _, p := range info.Permissions { if netPermissionMatches(p.Name, u) { if !b.allowRate(pluginID) { b.Audit(pluginID, "RATE_LIMIT", "net:"+u.Host) return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID) } return nil } } b.Audit(pluginID, "DENY", "undeclared network origin "+u.Scheme+"://"+u.Host) return fmt.Errorf("plugin %q has not declared net:%s://%s", pluginID, u.Scheme, u.Host) } func vmRefMapKey(driverID, name string) string { return strings.ToLower(strings.TrimSpace(driverID)) + "\x00" + strings.ToLower(strings.TrimSpace(name)) } // 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.Source != SourceBuiltin && info.Source != SourceBundled { 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) { b.Audit(pluginID, "RATE_LIMIT", perm) return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID) } return nil } // AllowRate checks that pluginID is active and within its 120 req/s Host API // rate window (used for zero-permission read-only calls such as i18n.getBundle). func (b *Broker) AllowRate(pluginID string) error { if b.reg == nil { return errors.New("registry unavailable") } if _, ok := b.reg.ManifestOf(pluginID); !ok { return fmt.Errorf("unknown plugin %q", pluginID) } if st := b.reg.StateOf(pluginID); st != StateActive && st != StateDegraded { return fmt.Errorf("plugin %q is not active (state=%s)", pluginID, st) } if !b.allowRate(pluginID) { b.Audit(pluginID, "RATE_LIMIT", "i18n.getBundle") return fmt.Errorf("plugin %q exceeded Host API rate limit", pluginID) } return nil } // hostCallsPerSecond is how many Host API calls one plugin may make per second. const hostCallsPerSecond = 120 func (b *Broker) allowRate(key string) bool { b.mu.Lock() defer b.mu.Unlock() now := time.Now() rw := b.rates[key] if rw == nil || now.Sub(rw.windowStart) >= time.Second { b.rates[key] = &rateWindow{windowStart: now, count: 1} return true } if rw.count >= hostCallsPerSecond { return false } rw.count++ return true } // fileOnlyTags are audit entries left out of the app log: successful routine // calls would push everything else out of it, and notifications already reach it // through the notifier. var fileOnlyTags = map[string]bool{ "HOST_API": true, "PANEL_CMD": true, "PANEL_UI": true, "CHANNEL_MESSAGE": true, "VM_STATE": true, "NOTIFY": true, } // Audit appends a redacted audit or stderr line to `/plugins/logs/.log` // with automatic rotation at 2 MiB (§6.1), and to the app log as `plugin:`. 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) // The app log has its own rate window, so a chatty plugin can't flood it. Line // breaks are folded so plugin text can't pose as another source's entry. if b.onLog != nil && !fileOnlyTags[tag] && b.allowRate("log:"+pluginID) { b.onLog("plugin:"+pluginID, "["+tag+"] "+strings.NewReplacer("\r", "", "\n", " ").Replace(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). It is the legacy form that names the // VM only; the driver is inferred when the plugin declares exactly one. func (b *Broker) SpawnManagedVMProcess(ctx context.Context, pluginID, vmName, exePath string, args []string, workDir string, env []string) (int, error) { return b.SpawnManagedVMProcessWithRef(ctx, pluginID, VMRef{Name: vmName}, exePath, args, workDir, env) } // resolveRefDriver completes and checks the driver ID of a ref a plugin sent: // an empty ID defaults to the plugin's only declared driver, and a plugin can // never act for a driver it did not declare. func (b *Broker) resolveRefDriver(pluginID, driverID string) (string, error) { declared := map[string]bool{} var ids []string if b.reg != nil { for _, id := range b.reg.DeclaredDriverIDs(pluginID) { if !declared[id] { declared[id] = true ids = append(ids, id) } } } driverID = strings.TrimSpace(driverID) if driverID == "" { switch len(ids) { case 0: return "", nil case 1: return ids[0], nil default: return "", fmt.Errorf("plugin %q declares several drivers; name driver_id", pluginID) } } if !declared[driverID] { b.Audit(pluginID, "DENY", fmt.Sprintf("plugin does not declare driver %q", driverID)) return "", fmt.Errorf("plugin %q does not declare driver %q", pluginID, driverID) } return driverID, nil } // SpawnManagedVMProcessWithRef starts a VM process for ref and puts it, with // every child it starts, in a per-VM job. Monitoring, affinity and window // lookup then cover the whole tree. func (b *Broker) SpawnManagedVMProcessWithRef(ctx context.Context, pluginID string, ref VMRef, 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 } vmName := strings.TrimSpace(ref.Name) driverID, err := b.resolveRefDriver(pluginID, ref.DriverID) if 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") } refKey := vmRefMapKey(driverID, vmName) if driverID != "" && vmName != "" { b.mu.Lock() busy := b.spawning[refKey] if cur := b.procsByRef[refKey]; cur != nil && !busy { select { case <-cur.done: default: busy = true } } if !busy { if b.spawning == nil { b.spawning = map[string]bool{} } b.spawning[refKey] = true } b.mu.Unlock() if busy { return 0, fmt.Errorf("VM %q of driver %q is already running", vmName, driverID) } defer func() { b.mu.Lock() delete(b.spawning, refKey) b.mu.Unlock() }() } build := func(breakaway bool) *exec.Cmd { cmd := exec.Command(exePath, args...) if workDir != "" { cmd.Dir = workDir } if len(env) > 0 { cmd.Env = append(os.Environ(), env...) } if breakaway { sidecarproc.ConfigureDetachedVMProcess(cmd) } else { sidecarproc.ConfigureNestedVMProcess(cmd) } return cmd } cmd := build(true) startErr := cmd.Start() if startErr != nil && sidecarproc.IsBreakawayDenied(startErr) { // The host itself runs in a job that forbids breakaway (some launchers // and CI sandboxes do). Start the VM inside that job instead; it is // still moved into its own per-VM job below. b.Audit(pluginID, "SPAWN_NOTE", fmt.Sprintf("vm=%s: job breakaway denied, starting inside the host job", vmName)) cmd = build(false) startErr = cmd.Start() } if startErr != nil { b.Audit(pluginID, "SPAWN_ERR", fmt.Sprintf("vm=%s exe=%s err=%v", vmName, filepath.Base(exePath), startErr)) return 0, startErr } pid := cmd.Process.Pid job, jobErr := sidecarproc.NewVMJob() if jobErr == nil { if jobErr = job.Assign(pid); jobErr != nil { job.Close() job = nil } } else { job = nil } if jobErr != nil { b.Audit(pluginID, "JOB_ERR", fmt.Sprintf("vm=%s pid=%d: %v (only the launcher process is tracked)", vmName, pid, jobErr)) } if err := sidecarproc.ResumeVMProcess(pid); err != nil { _ = cmd.Process.Kill() _ = cmd.Wait() job.Close() b.Audit(pluginID, "SPAWN_ERR", fmt.Sprintf("vm=%s exe=%s err=%v", vmName, filepath.Base(exePath), err)) return 0, err } mp := &ManagedProcess{ PID: pid, PluginID: pluginID, VMName: vmName, DriverID: driverID, cmd: cmd, job: job, done: make(chan struct{}), } b.mu.Lock() b.procs[pid] = mp if driverID != "" && vmName != "" { b.procsByRef[refKey] = mp } b.mu.Unlock() b.Audit(pluginID, "SPAWN", fmt.Sprintf("vm=%s driver=%s pid=%d exe=%s", vmName, driverID, pid, filepath.Base(exePath))) go func() { _ = cmd.Wait() if job != nil { job.RootExited() <-job.Done() } close(mp.done) b.mu.Lock() delete(b.procs, pid) if b.procsByRef[refKey] == mp { delete(b.procsByRef, refKey) } onExit := b.onVMExit b.mu.Unlock() job.Close() b.Audit(pluginID, "EXIT", fmt.Sprintf("vm=%s driver=%s pid=%d", vmName, driverID, pid)) if onExit != nil && driverID != "" && vmName != "" { onExit(driverID, vmName) } }() return pid, nil } // stopManagedWaitTimeout bounds how long host/vm.stop waits for the OS to reap // a terminated VM job (Windows TerminateJobObject finishes asynchronously). const stopManagedWaitTimeout = 5 * time.Second // terminateManaged stops every process of a managed VM and waits for the job // to drain so an immediate host/vm.isRunning or host/vm.spawn observes it gone. func terminateManaged(mp *ManagedProcess) error { if mp == nil { return nil } if mp.done != nil { select { case <-mp.done: return nil default: } } var err error if mp.job != nil { err = mp.job.Terminate() } else if mp.cmd != nil && mp.cmd.Process != nil { err = mp.cmd.Process.Kill() } if err != nil { if mp.done != nil { select { case <-mp.done: return nil default: } } return err } if mp.done != nil { timer := time.NewTimer(stopManagedWaitTimeout) defer timer.Stop() select { case <-mp.done: case <-timer.C: return fmt.Errorf("VM %q is still shutting down", mp.VMName) } } return nil } // StopManagedVMProcess terminates a host-managed VM process tree 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 { return nil } if mp.PluginID != pluginID { return fmt.Errorf("PID %d is not owned by plugin %q", pid, pluginID) } return terminateManaged(mp) } // StopManagedVMProcessByRef terminates the VM job of ref. func (b *Broker) StopManagedVMProcessByRef(pluginID string, ref VMRef) error { if err := b.Authorize(pluginID, "vm:control"); err != nil { return err } driverID, err := b.resolveRefDriver(pluginID, ref.DriverID) if err != nil { return err } b.mu.Lock() mp := b.procsByRef[vmRefMapKey(driverID, ref.Name)] b.mu.Unlock() if mp == nil { return nil } if mp.PluginID != pluginID { return fmt.Errorf("VM %q is not owned by plugin %q", ref.Name, pluginID) } return terminateManaged(mp) } // 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 } } // IsManagedVMRunningForPlugin reports whether ref's VM job still holds a // process and pluginID owns it. func (b *Broker) IsManagedVMRunningForPlugin(pluginID string, ref VMRef) bool { driverID, err := b.resolveRefDriver(pluginID, ref.DriverID) if err != nil { return false } b.mu.Lock() mp := b.procsByRef[vmRefMapKey(driverID, ref.Name)] b.mu.Unlock() if mp == nil || mp.PluginID != pluginID { return false } select { case <-mp.done: return false default: return true } } func (b *Broker) managedByRef(driverID, name string) *ManagedProcess { b.mu.Lock() defer b.mu.Unlock() mp := b.procsByRef[vmRefMapKey(driverID, name)] if mp == nil { return nil } select { case <-mp.done: return nil default: return mp } } // IsManagedVMRunning reports whether the host spawned a still-running VM for // the driver and name. func (b *Broker) IsManagedVMRunning(driverID, name string) bool { return b.managedByRef(driverID, name) != nil } // ManagedVMPIDs lists every process of a host-spawned VM, or nil when the // host did not spawn one. Without a job object it holds the launcher only. func (b *Broker) ManagedVMPIDs(driverID, name string) []uint32 { mp := b.managedByRef(driverID, name) if mp == nil { return nil } if mp.job != nil { return mp.job.PIDs() } return []uint32{uint32(mp.PID)} } // SetManagedVMAffinity limits every current and future process of the VM's // job to mask; a zero mask lifts the limit. func (b *Broker) SetManagedVMAffinity(driverID, name string, mask uint64) error { mp := b.managedByRef(driverID, name) if mp == nil || mp.job == nil { return fmt.Errorf("VM %q of driver %q has no managed process job", name, driverID) } return mp.job.SetAffinity(mask) } // reportableVMStates are the states a driver may report. var reportableVMStates = map[string]bool{ "stopped": true, "starting": true, "running": true, "stopping": true, "suspended": true, "broken": true, } // ReportVMState accepts a driver's report about a VM it owns. A plugin can // only report for drivers its manifest declares. func (b *Broker) ReportVMState(pluginID string, rep ReportedVMState) error { if err := b.Authorize(pluginID, "driver:vm"); err != nil { return err } driverID, err := b.resolveRefDriver(pluginID, rep.Ref.DriverID) if err != nil { return err } if driverID == "" { return fmt.Errorf("plugin %q declares no driver to report for", pluginID) } rep.Ref.DriverID = driverID rep.Ref.Name = strings.TrimSpace(rep.Ref.Name) if rep.Ref.Name == "" { return errors.New("reported state needs a VM name") } rep.State = strings.ToLower(strings.TrimSpace(rep.State)) if !reportableVMStates[rep.State] { return fmt.Errorf("reported state %q is not allowed", rep.State) } b.mu.Lock() fn := b.onVMState b.mu.Unlock() if fn == nil { return errors.New("VM state reports are not accepted") } if err := fn(pluginID, rep); err != nil { b.Audit(pluginID, "DENY", fmt.Sprintf("vm state report for %s/%s: %v", driverID, rep.Ref.Name, err)) return err } b.Audit(pluginID, "VM_STATE", fmt.Sprintf("vm=%s driver=%s state=%s", rep.Ref.Name, driverID, rep.State)) return nil }