Files
Reims-Go/internal/plugin/rpc.go
T
NwflowerandClaude Opus 5.5 44e2174fff fix: harden guest driver host APIs
- run elevated actions as fixed System32 tools instead of a hidden subcommand
- require a SHA-256 for plugin downloads
- keep records of secret files that could not be deleted, and never overwrite
  files the host did not create
- stop two concurrent requests from starting the same VM
- drop invalid endpoints instead of failing the whole VM list, and reject ssh
  users and IPv6 zones that could inject command-line text
- accept driver screenshots only at the requested path
- do not treat an unreadable guest phase as normal

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 09:07:46 -07:00

344 lines
7.7 KiB
Go

package plugin
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"strings"
"sync"
"sync/atomic"
)
const maxRPCFrameBytes = 8 << 20 // 8 MiB per JSON-RPC frame (large blobs go via file paths, §8)
// RPCMethodNotFound is the code a peer answers for a method it does not serve.
const RPCMethodNotFound = -32601
// RPCError is a JSON-RPC 2.0 error object.
type RPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (e *RPCError) Error() string {
return fmt.Sprintf("rpc error %d: %s", e.Code, e.Message)
}
type rpcEnvelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *RPCError `json:"error,omitempty"`
}
// RPCRequestHandler handles inbound JSON-RPC requests from the peer.
type RPCRequestHandler func(ctx context.Context, params json.RawMessage) (any, error)
// RPCConn implements bidirectional Content-Length framed JSON-RPC 2.0 over
// stdio pipes with a single writer goroutine and bounded queue (§8).
type RPCConn struct {
r *bufio.Reader
w io.Writer
writeCh chan []byte
closeCh chan struct{}
closeOnce sync.Once
nextID atomic.Uint64
mu sync.Mutex
pending map[string]chan rpcEnvelope
handlers map[string]RPCRequestHandler
inboundSem chan struct{}
closed bool
doneCh chan struct{}
}
// NewRPCConn starts reader and single-writer goroutines over r and w.
func NewRPCConn(r io.Reader, w io.Writer) *RPCConn {
c := &RPCConn{
r: bufio.NewReaderSize(r, 64*1024),
w: w,
writeCh: make(chan []byte, 64),
closeCh: make(chan struct{}),
pending: make(map[string]chan rpcEnvelope),
handlers: make(map[string]RPCRequestHandler),
inboundSem: make(chan struct{}, 32),
doneCh: make(chan struct{}),
}
go c.writeLoop()
go c.readLoop()
return c
}
// Handle registers a handler for inbound peer requests of method.
func (c *RPCConn) Handle(method string, h RPCRequestHandler) {
c.mu.Lock()
c.handlers[method] = h
c.mu.Unlock()
}
// Call sends a JSON-RPC 2.0 request and waits for the response or ctx cancellation.
func (c *RPCConn) Call(ctx context.Context, method string, params any, out any) error {
idNum := c.nextID.Add(1)
idKey := strconv.FormatUint(idNum, 10)
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
env := rpcEnvelope{
JSONRPC: "2.0",
ID: json.RawMessage(idKey),
Method: method,
Params: rawParams,
}
payload, err := json.Marshal(env)
if err != nil {
return err
}
respCh := make(chan rpcEnvelope, 1)
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return errors.New("rpc connection closed")
}
c.pending[idKey] = respCh
c.mu.Unlock()
defer func() {
c.mu.Lock()
delete(c.pending, idKey)
c.mu.Unlock()
}()
if err := c.enqueue(ctx, payload); err != nil {
return err
}
select {
case resp, ok := <-respCh:
if !ok {
return errors.New("rpc connection closed while awaiting response")
}
if resp.Error != nil {
return resp.Error
}
if out != nil && len(resp.Result) > 0 && string(resp.Result) != "null" {
return json.Unmarshal(resp.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
case <-c.closeCh:
return errors.New("rpc connection closed")
case <-c.doneCh:
return errors.New("rpc connection closed")
}
}
// Notify sends a JSON-RPC 2.0 notification (no response expected).
func (c *RPCConn) Notify(ctx context.Context, method string, params any) error {
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
env := rpcEnvelope{
JSONRPC: "2.0",
Method: method,
Params: rawParams,
}
payload, err := json.Marshal(env)
if err != nil {
return err
}
return c.enqueue(ctx, payload)
}
func (c *RPCConn) enqueue(ctx context.Context, payload []byte) error {
select {
case c.writeCh <- payload:
return nil
case <-ctx.Done():
return ctx.Err()
case <-c.closeCh:
return errors.New("rpc connection closed")
}
}
func (c *RPCConn) writeLoop() {
for {
select {
case payload := <-c.writeCh:
header := fmt.Sprintf("Content-Length: %d\r\n\r\n", len(payload))
if _, err := io.WriteString(c.w, header); err != nil {
c.Close()
return
}
if _, err := c.w.Write(payload); err != nil {
c.Close()
return
}
case <-c.closeCh:
return
}
}
}
func (c *RPCConn) readLoop() {
defer func() {
c.Close()
close(c.doneCh)
}()
for {
frame, err := readContentLengthFrame(c.r)
if err != nil {
return
}
var env rpcEnvelope
if err := json.Unmarshal(frame, &env); err != nil {
continue
}
if env.Method != "" {
// Bounded inbound concurrency so a misbehaving sidecar cannot spawn
// unbounded goroutines in the host.
select {
case c.inboundSem <- struct{}{}:
go func(e rpcEnvelope) {
defer func() { <-c.inboundSem }()
c.dispatchInbound(e)
}(env)
case <-c.closeCh:
return
}
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
c.mu.Lock()
ch := c.pending[key]
delete(c.pending, key)
if ch != nil {
select {
case ch <- env:
default:
}
}
c.mu.Unlock()
}
}
}
func (c *RPCConn) dispatchInbound(env rpcEnvelope) {
c.mu.Lock()
h := c.handlers[env.Method]
c.mu.Unlock()
if h == nil {
if len(env.ID) > 0 {
c.sendResponse(env.ID, nil, &RPCError{Code: RPCMethodNotFound, Message: "method not found: " + env.Method})
}
return
}
res, err := h(context.Background(), env.Params)
if len(env.ID) == 0 {
return // notification
}
if err != nil {
c.sendResponse(env.ID, nil, &RPCError{Code: -32000, Message: err.Error()})
return
}
c.sendResponse(env.ID, res, nil)
}
func (c *RPCConn) sendResponse(id json.RawMessage, result any, rpcErr *RPCError) {
env := rpcEnvelope{
JSONRPC: "2.0",
ID: id,
Error: rpcErr,
}
if rpcErr == nil {
if result == nil {
env.Result = json.RawMessage("null")
} else if b, err := json.Marshal(result); err == nil {
env.Result = b
}
}
if b, err := json.Marshal(env); err == nil {
_ = c.enqueue(context.Background(), b)
}
}
// Close closes the RPC connection and fails all pending outbound calls.
func (c *RPCConn) Close() {
c.closeOnce.Do(func() {
close(c.closeCh)
c.mu.Lock()
c.closed = true
for id := range c.pending {
delete(c.pending, id)
}
c.mu.Unlock()
})
}
func readContentLengthFrame(r *bufio.Reader) ([]byte, error) {
const (
maxHeaderLines = 64
maxHeaderBytes = 8 * 1024
)
contentLen := -1
for lines := 0; ; lines++ {
if lines >= maxHeaderLines {
return nil, errors.New("RPC header line limit exceeded")
}
var rawLine []byte
for {
chunk, isPrefix, err := r.ReadLine()
if err != nil {
return nil, err
}
if len(rawLine)+len(chunk) > maxHeaderBytes {
return nil, errors.New("RPC header line exceeds 8 KiB limit")
}
rawLine = append(rawLine, chunk...)
if !isPrefix {
break
}
}
line := string(rawLine)
if line == "" {
break
}
k, v, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 || n > maxRPCFrameBytes {
return nil, fmt.Errorf("invalid Content-Length %q", v)
}
contentLen = n
}
}
if contentLen < 0 {
return nil, errors.New("missing Content-Length header")
}
buf := make([]byte, contentLen)
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
return buf, nil
}