oficina / equipo Public

security: cancellable writes to Pi, bounded text and queues

Astra's S2 round, findings 2 and 6. Writes to Pi's stdin give up with
their context (a separate write lock, never held by a waiting caller),
so a Pi that stops reading cannot hold the runner; a cancelled run asks
Pi to stop aside and the namespace is killed regardless. The client
keeps at most 16 MiB of records (Pi waits for the rest), a record over
8 MiB ends the stream, events carry no tool arguments over 64 KiB, and
a reply over 1 MiB ends the run with its usage incomplete.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 36efd3c1bdebc93b1be1fa60c8ffa2ec23bcb85f parent 0da84b4
8 files changed, +299 −23
  • internal/fakepi/fake.go +6 −1
  • internal/runner/provider/pi/decode.go +14 −1
  • internal/runner/provider/pi/launcher.go +13 −5
  • internal/runner/provider/pi/rpc.go +73 −13
  • internal/runner/provider/pi/rpc_test.go +150 −0
  • internal/runner/thin/pistep.go +21 −3
  • internal/runner/thin/pistep_test.go +15 −0
  • scripts/runner-reference-allowlist.json +7 −0
diff --git a/internal/fakepi/fake.go b/internal/fakepi/fake.go
index d103fbe3..34543c58 100644
--- a/internal/fakepi/fake.go
+++ b/internal/fakepi/fake.go
@@ -23,7 +23,7 @@
// answers; "read:<path>" reads a file (asked when outside the
// confinement); "keyrefused" fails as a 401, "ratelimited" as a 429 after
// Pi's three retries, "nousage" ends with no message_end, "endnousage" ends properly with no usage, "sleep:<ms>"
-// pauses mid-reply, "answeredby:<model>" reports that model as the one
+// pauses mid-reply, "flood:<n>" replies with n bytes, "answeredby:<model>" reports that model as the one
// that answered, "unknown-event" emits a record of a type Equipo does
// not know.
package fakepi
@@ -53,6 +53,7 @@ var (
readWord = regexp.MustCompile(`read:(\S+)`)
sleepWord = regexp.MustCompile(`sleep:([0-9]+)`)
answeredWord = regexp.MustCompile(`answeredby:(\S+)`)
+ floodWord = regexp.MustCompile(`flood:([0-9]+)`)
)
type fake struct {
@@ -363,6 +364,10 @@ func (f *fake) run(prompt string) {
default:
reply = "ok " + strings.Join(notes, " ")
}
+ if m := floodWord.FindStringSubmatch(prompt); m != nil {
+ n, _ := strconv.Atoi(m[1])
+ reply = strings.Repeat("f", n)
+ }
if m := sleepWord.FindStringSubmatch(prompt); m != nil {
ms, _ := strconv.Atoi(m[1])
select {
diff --git a/internal/runner/provider/pi/decode.go b/internal/runner/provider/pi/decode.go
index cfb31e7d..2722a352 100644
--- a/internal/runner/provider/pi/decode.go
+++ b/internal/runner/provider/pi/decode.go
@@ -151,7 +151,7 @@ func (d *Decoder) Decode(line []byte) ([]provider.Event, error) {
d.lastStop, d.lastError = m.StopReason, m.ErrorMessage
return event(KindUsage, usageOf(m.Model, m.Usage)), nil
case "tool_execution_start":
- return event(KindToolCall, ToolCall{ID: r.ToolCallID, Tool: r.ToolName, Args: r.Args}), nil
+ return event(KindToolCall, ToolCall{ID: r.ToolCallID, Tool: r.ToolName, Args: clipArgs(r.Args)}), nil
case "tool_execution_end":
return event(KindToolResult, ToolResult{ID: r.ToolCallID, Tool: r.ToolName, IsError: r.IsError}), nil
case "extension_ui_request":
@@ -163,6 +163,7 @@ func (d *Decoder) Decode(line []byte) ([]provider.Event, error) {
}
if json.Unmarshal(line, &raw) == nil && r.Title == askTitle {
_ = json.Unmarshal([]byte(raw.Message), &a.Call)
+ a.Call.Args = clipArgs(a.Call.Args)
}
return event(KindAsk, a), nil
}
@@ -220,6 +221,18 @@ func usageOf(model string, raw json.RawMessage) Usage {
return out
}
+// maxEventArgs bounds a tool call's arguments in an event: the runner
+// reads them only for the activity line.
+const maxEventArgs = 64 << 10
+
+// clipArgs drops arguments over maxEventArgs.
+func clipArgs(raw json.RawMessage) json.RawMessage {
+ if len(raw) > maxEventArgs {
+ return nil
+ }
+ return raw
+}
+
// askTitle is the title Equipo's extension gives its question.
const askTitle = "equipo:tool_call"
diff --git a/internal/runner/provider/pi/launcher.go b/internal/runner/provider/pi/launcher.go
index 819b8bb9..0fed68fe 100644
--- a/internal/runner/provider/pi/launcher.go
+++ b/internal/runner/provider/pi/launcher.go
@@ -63,11 +63,15 @@ func (l *Launcher) Open(ctx context.Context, launch provider.Launch) (provider.S
if argv == nil {
return provider.Session{}, provider.ErrPolicy
}
+ return l.openWith(ctx, launch, argv)
+}
+
+func (l *Launcher) openWith(ctx context.Context, launch provider.Launch, argv []string) (provider.Session, error) {
proc, err := l.host.Start(ctx, launch, argv)
if err != nil {
return provider.Session{}, err
}
- s := &session{launch: launch, process: proc, client: NewClient(proc.Stdout(), proc.Stdin()), decoder: &Decoder{}, events: make(chan provider.Event, 256), asks: map[string]bool{}}
+ s := &session{launch: launch, process: proc, client: NewClient(proc.Stdout(), proc.Stdin()), decoder: &Decoder{}, events: make(chan provider.Event, 64), asks: map[string]bool{}}
sctx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
r, err := s.client.Call(sctx, map[string]any{"type": "get_state"})
@@ -102,6 +106,7 @@ func (s *session) read(id string) {
s.mu.Lock()
evs, err := s.decoder.Decode(line)
s.mu.Unlock()
+ s.client.Release(len(line))
if err != nil {
continue
}
@@ -162,7 +167,7 @@ func (l *Launcher) StartTurn(ctx context.Context, sess provider.Session, t provi
// Respond answers the extension's question: Behavior "allow" lets the
// call run; anything else blocks it.
-func (l *Launcher) Respond(_ context.Context, sess provider.Session, a provider.Answer) error {
+func (l *Launcher) Respond(ctx context.Context, sess provider.Session, a provider.Answer) error {
s, err := l.state(sess)
if err != nil {
return err
@@ -174,11 +179,12 @@ func (l *Launcher) Respond(_ context.Context, sess provider.Session, a provider.
if !pending {
return provider.ErrIdentity
}
- return s.client.Send(map[string]any{"type": "extension_ui_response", "id": a.RequestID, "confirmed": a.Behavior == "allow"})
+ return s.client.Send(ctx, map[string]any{"type": "extension_ui_response", "id": a.RequestID, "confirmed": a.Behavior == "allow"})
}
// Interrupt cancels any question Pi waits on (an abort does not end a
-// pending dialog), then aborts the run.
+// pending dialog), then aborts the run. It gives up when ctx ends: the
+// run's end is the namespace's kill, never Pi's answer.
func (l *Launcher) Interrupt(ctx context.Context, sess provider.Session) error {
s, err := l.state(sess)
if err != nil {
@@ -193,7 +199,9 @@ func (l *Launcher) Interrupt(ctx context.Context, sess provider.Session) error {
s.mu.Unlock()
slices.Sort(ids)
for _, id := range ids {
- _ = s.client.Send(map[string]any{"type": "extension_ui_response", "id": id, "cancelled": true})
+ if err := s.client.Send(ctx, map[string]any{"type": "extension_ui_response", "id": id, "cancelled": true}); err != nil {
+ return err
+ }
}
_, err = s.client.Call(ctx, map[string]any{"type": "abort"})
return err
diff --git a/internal/runner/provider/pi/rpc.go b/internal/runner/provider/pi/rpc.go
index 424c7591..09b3547f 100644
--- a/internal/runner/provider/pi/rpc.go
+++ b/internal/runner/provider/pi/rpc.go
@@ -14,14 +14,25 @@ import (
// answered by a response record of the same id on stdout among the
// session's events. Records are split on LF only (Pi's framing rule).
type Client struct {
- mu sync.Mutex
+ mu sync.Mutex
+ // wmu orders writes; it is never held by a caller that waits, so a
+ // Pi that stops reading cannot hold the client.
+ wmu sync.Mutex
w io.Writer
next int
pending map[string]chan Response
closed bool
// Records are every record that is not a command's response, in
- // order; closed when stdout ends.
+ // order; closed when stdout ends or a record is over the size limit.
+ // The reader of Records hands each one's bytes back with Release.
Records <-chan []byte
+
+ // queued is how many bytes of Records are taken and not released;
+ // the client stops reading Pi's stdout while they are over budget.
+ qmu sync.Mutex
+ qcond *sync.Cond
+ queued int
+ budget int
}
// Response is a command's answer.
@@ -36,18 +47,27 @@ type Response struct {
// ErrClosed: Pi's stdout ended.
var ErrClosed = errors.New("pi: the process ended")
-// maxRecord bounds one record (a tool result can be large).
-const maxRecord = 16 << 20
+// maxRecord bounds one record (a tool result can be large); maxQueued
+// bounds the bytes waiting in the client.
+const (
+ maxRecord = 8 << 20
+ maxQueued = 16 << 20
+)
// NewClient reads r until it ends.
func NewClient(r io.Reader, w io.Writer) *Client {
+ return newClientLimits(r, w, maxRecord, maxQueued)
+}
+
+func newClientLimits(r io.Reader, w io.Writer, record, queued int) *Client {
records := make(chan []byte, 256)
- c := &Client{w: w, pending: map[string]chan Response{}, Records: records}
+ c := &Client{w: w, pending: map[string]chan Response{}, Records: records, budget: queued}
+ c.qcond = sync.NewCond(&c.qmu)
go func() {
defer close(records)
defer c.fail()
s := bufio.NewScanner(r)
- s.Buffer(make([]byte, 0, 64<<10), maxRecord)
+ s.Buffer(make([]byte, 0, min(64<<10, record)), record)
for s.Scan() {
line := append([]byte(nil), s.Bytes()...)
if len(line) == 0 {
@@ -67,12 +87,38 @@ func NewClient(r io.Reader, w io.Writer) *Client {
continue
}
}
+ c.take(len(line))
records <- line
}
}()
return c
}
+// take waits until n more bytes fit the budget (one record always does
+// when nothing else waits).
+func (c *Client) take(n int) {
+ c.qmu.Lock()
+ defer c.qmu.Unlock()
+ for c.queued > 0 && c.queued+n > c.budget {
+ c.qcond.Wait()
+ }
+ c.queued += n
+}
+
+// Release hands back a record's bytes once it has been read.
+func (c *Client) Release(n int) {
+ c.qmu.Lock()
+ c.queued -= n
+ c.qmu.Unlock()
+ c.qcond.Broadcast()
+}
+
+func (c *Client) queuedBytes() int {
+ c.qmu.Lock()
+ defer c.qmu.Unlock()
+ return c.queued
+}
+
func (c *Client) fail() {
c.mu.Lock()
defer c.mu.Unlock()
@@ -83,19 +129,33 @@ func (c *Client) fail() {
}
}
-// Send writes one record as a line.
-func (c *Client) Send(v any) error {
+// Send writes one record as a line. It gives up when ctx ends: a Pi that
+// stops reading its stdin holds only the write itself, which ends when
+// the namespace is killed and the pipe closes.
+func (c *Client) Send(ctx context.Context, v any) error {
raw, err := json.Marshal(v)
if err != nil {
return err
}
c.mu.Lock()
- defer c.mu.Unlock()
- if c.closed {
+ closed := c.closed
+ c.mu.Unlock()
+ if closed {
return ErrClosed
}
- _, err = c.w.Write(append(raw, '\n'))
- return err
+ done := make(chan error, 1)
+ go func() {
+ c.wmu.Lock()
+ defer c.wmu.Unlock()
+ _, err := c.w.Write(append(raw, '\n'))
+ done <- err
+ }()
+ select {
+ case err := <-done:
+ return err
+ case <-ctx.Done():
+ return ctx.Err()
+ }
}
// Call sends a command and waits for its response.
@@ -114,7 +174,7 @@ func (c *Client) Call(ctx context.Context, command map[string]any) (Response, er
for k, v := range command {
cmd[k] = v
}
- if err := c.Send(cmd); err != nil {
+ if err := c.Send(ctx, cmd); err != nil {
c.mu.Lock()
delete(c.pending, id)
c.mu.Unlock()
diff --git a/internal/runner/provider/pi/rpc_test.go b/internal/runner/provider/pi/rpc_test.go
new file mode 100644
index 00000000..6c8edb98
--- /dev/null
+++ b/internal/runner/provider/pi/rpc_test.go
@@ -0,0 +1,150 @@
+package pi
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/runner/provider"
+)
+
+// A Pi that stops reading its stdin cannot hold the runner: a write
+// gives up when its context ends, a command too, and other writes wait
+// their turn without blocking the client.
+func TestClientWritesAreCancellable(t *testing.T) {
+ stdinR, stdinW := io.Pipe() // nobody reads stdinR
+ defer stdinR.Close()
+ stdoutR, stdoutW := io.Pipe()
+ defer stdoutW.Close()
+ c := NewClient(stdoutR, stdinW)
+ for _, call := range []func(context.Context) error{
+ func(ctx context.Context) error { return c.Send(ctx, map[string]string{"type": "abort"}) },
+ func(ctx context.Context) error { _, err := c.Call(ctx, map[string]any{"type": "abort"}); return err },
+ } {
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ start := time.Now()
+ err := call(ctx)
+ cancel()
+ if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 2*time.Second {
+ t.Fatalf("a write to a stdin nobody reads: %v after %v", err, time.Since(start))
+ }
+ }
+}
+
+// stuckProcess is a Pi whose stdin nobody reads; its stdout answers
+// get_state, then says nothing more.
+type stuckProcess struct {
+ stdinR *io.PipeReader
+ stdinW *io.PipeWriter
+ stdoutR *io.PipeReader
+ stdoutW *io.PipeWriter
+}
+
+func (p *stuckProcess) Stdin() io.WriteCloser { return p.stdinW }
+func (p *stuckProcess) Stdout() io.ReadCloser { return p.stdoutR }
+func (p *stuckProcess) Stderr() io.ReadCloser { return io.NopCloser(strings.NewReader("")) }
+func (p *stuckProcess) ID() string { return "stuck" }
+func (p *stuckProcess) Wait(ctx context.Context) (provider.Exit, error) {
+ <-ctx.Done()
+ return provider.Exit{}, ctx.Err()
+}
+
+type stuckHost struct{ p *stuckProcess }
+
+func (h stuckHost) Start(ctx context.Context, l provider.Launch, argv []string) (provider.Process, error) {
+ go func() {
+ // Read get_state, answer it, then stop reading for good.
+ buf := make([]byte, 4096)
+ n, _ := h.p.stdinR.Read(buf)
+ var cmd struct{ ID string }
+ json.Unmarshal(buf[:n], &cmd)
+ raw, _ := json.Marshal(map[string]any{"type": "response", "id": cmd.ID, "command": "get_state", "success": true, "data": map[string]any{"sessionId": "01234567-89ab", "model": map[string]string{"id": l.Selection.Model, "provider": l.Selection.Provider}}})
+ h.p.stdoutW.Write(append(raw, '\n'))
+ // And a question it waits on, so an interrupt has a dialog to
+ // cancel first.
+ h.p.stdoutW.Write([]byte(`{"type":"extension_ui_request","id":"ui-1","method":"confirm","title":"equipo:tool_call","message":"{}"}` + "\n"))
+ }()
+ return h.p, nil
+}
+
+func TestLauncherInterruptIsBounded(t *testing.T) {
+ p := &stuckProcess{}
+ p.stdinR, p.stdinW = io.Pipe()
+ p.stdoutR, p.stdoutW = io.Pipe()
+ defer p.stdoutW.Close()
+ defer p.stdinR.Close()
+ l, _ := New(stuckHost{p})
+ sess, err := l.openWith(context.Background(), provider.Launch{Selection: provider.Selection{Provider: "tensorx", Model: "m"}}, []string{"/opt/node"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ events, _ := l.Events(context.Background(), sess)
+ if e := <-events; e.Kind != KindAsk {
+ t.Fatalf("event %s", e.Kind)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ if err := l.Interrupt(ctx, sess); err == nil || time.Since(start) > 2*time.Second {
+ t.Fatalf("an interrupt Pi never reads: %v after %v", err, time.Since(start))
+ }
+ ctx2, cancel2 := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel2()
+ if err := l.StartTurn(ctx2, sess, provider.Turn{ID: "t", Prompt: "x"}); err == nil {
+ t.Fatal("a prompt Pi never reads went through")
+ }
+}
+
+// What Pi sends is held to a budget: records wait in the client only up
+// to its bytes, Pi waits for the rest (it honours stdout backpressure),
+// and a record over the size limit ends the stream.
+func TestClientQueueIsBounded(t *testing.T) {
+ stdoutR, stdoutW := io.Pipe()
+ defer stdoutW.Close()
+ c := newClientLimits(stdoutR, io.Discard, 1000, 300)
+ line := strings.Repeat("x", 90)
+ go func() {
+ for range 20 {
+ if _, err := stdoutW.Write([]byte(`{"type":"` + line + `"}` + "\n")); err != nil {
+ return
+ }
+ }
+ }()
+ time.Sleep(300 * time.Millisecond)
+ if q := c.queuedBytes(); q > 300 || len(c.Records) > 3 {
+ t.Fatalf("queued %d bytes in %d records with a budget of 300", q, len(c.Records))
+ }
+ // Taking one lets one more in.
+ got := <-c.Records
+ c.Release(len(got))
+ time.Sleep(100 * time.Millisecond)
+ if q := c.queuedBytes(); q > 300 || q == 0 {
+ t.Fatalf("queued %d", q)
+ }
+
+ big := newClientLimits(strings.NewReader(`{"type":"`+strings.Repeat("y", 2000)+`"}`+"\n"+`{"type":"after"}`+"\n"), io.Discard, 1000, 300)
+ n := 0
+ for range big.Records {
+ n++
+ }
+ if n != 0 {
+ t.Fatalf("an oversized record did not end the stream: %d records after it", n)
+ }
+}
+
+// A tool call's arguments in an event are clipped; the call itself is
+// Pi's to run.
+func TestDecodeClipsToolArguments(t *testing.T) {
+ d := &Decoder{}
+ evs, err := d.Decode([]byte(`{"type":"tool_execution_start","toolCallId":"c","toolName":"write","args":{"content":"` + strings.Repeat("z", 200000) + `"}}`))
+ if err != nil || len(evs) != 1 {
+ t.Fatal(err)
+ }
+ if len(evs[0].Payload) > maxEventArgs+1024 {
+ t.Fatalf("payload of %d bytes", len(evs[0].Payload))
+ }
+}
diff --git a/internal/runner/thin/pistep.go b/internal/runner/thin/pistep.go
index a1bcefd2..e91a739e 100644
--- a/internal/runner/thin/pistep.go
+++ b/internal/runner/thin/pistep.go
@@ -30,6 +30,11 @@ type PiOptions struct {
Install pi.Install
}
+// piTextLimit bounds the reply text a Pi run keeps: a step's summary
+// and a question's answer are far shorter. A run that goes past it is
+// ended, failed, with its usage incomplete.
+var piTextLimit = 1 << 20
+
// reasonHeld is a step's run held by the metered guard: the slot is
// taken, the budget reached or the spend unknown (connectors spec §2.3).
// The step waits, deferred, and is looked at again when the
@@ -274,9 +279,13 @@ func (e *Engineer) piRun(ctx context.Context, l *pi.Launcher, sess provider.Sess
for {
select {
case <-tctx.Done():
- ictx, stop := context.WithTimeout(context.Background(), 2*time.Second)
- _ = l.Interrupt(ictx, sess)
- stop()
+ // Ask Pi to stop, aside: the namespace is killed next
+ // (stopStep) whether or not Pi ever reads the request.
+ go func() {
+ ictx, stop := context.WithTimeout(context.Background(), 2*time.Second)
+ defer stop()
+ _ = l.Interrupt(ictx, sess)
+ }()
return finish(piCancelled(ctx))
case ev, ok := <-events:
if !ok {
@@ -291,6 +300,15 @@ func (e *Engineer) piRun(ctx context.Context, l *pi.Launcher, sess provider.Sess
case pi.KindDelta:
var d pi.Delta
_ = json.Unmarshal(ev.Payload, &d)
+ if text.Len()+len(d.Text) > piTextLimit {
+ tail.add("The reply was too long")
+ go func() {
+ ictx, stop := context.WithTimeout(context.Background(), 2*time.Second)
+ defer stop()
+ _ = l.Interrupt(ictx, sess)
+ }()
+ return finish(stepResult{reason: "provider_failed"})
+ }
text.WriteString(d.Text)
if s := spec.stream; s != nil {
s.mark(&s.timing.FirstEventMs)
diff --git a/internal/runner/thin/pistep_test.go b/internal/runner/thin/pistep_test.go
index 056b2783..b500ebe0 100644
--- a/internal/runner/thin/pistep_test.go
+++ b/internal/runner/thin/pistep_test.go
@@ -481,3 +481,18 @@ func TestPiEndWithoutUsagePausesTheConnection(t *testing.T) {
t.Fatalf("spend unknown %v, slot free %v", r.conn().SpendUnknown, r.slotFree())
}
}
+
+// A reply over the text the runner keeps ends the run, its usage
+// incomplete, so the connection's spend is unknown. (Review's verdict,
+// given through Equipo's tool before the flood, still stands.)
+func TestPiOversizedReply(t *testing.T) {
+ was := piTextLimit
+ piTextLimit = 1000
+ t.Cleanup(func() { piTextLimit = was })
+ r := newPiRig(t, fakePiInstall(t), bigBudget)
+ leave(t)
+ rep := r.runReview("flood:50000", 1)
+ if !strings.Contains(rep.LogTail, "The reply was too long") || !r.conn().SpendUnknown || len(rep.Summary) > 1000 {
+ t.Fatalf("report %s %s summary %d, spend unknown %v", rep.State, rep.Reason, len(rep.Summary), r.conn().SpendUnknown)
+ }
+}
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index f1bae24b..6ab76dda 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -14335,6 +14335,13 @@
"count": 1,
"reason": "Tests of the pinned Pi harness: Node, its npm tree and Pi's RPC mode (connectors spec S2)."
},
+ {
+ "path": "internal/runner/provider/pi/rpc_test.go",
+ "line_sha256": "c988ad5d7780ee838f48422e93c18b9199bb041f1b1583ab1c7a49053b5a4c14",
+ "match": "node",
+ "count": 1,
+ "reason": "Tests of the pinned Pi harness: Node, its npm tree and Pi's RPC mode (connectors spec S2)."
+ },
{
"path": "internal/runner/provider/pi_extension.ts",
"line_sha256": "a1247a361dad140ae013570f1d32d3ca28c5fd2bffc05193baf4a0681aeb44af",