security: pin the mounted Pi tree, resolve links, unknown usage
Astra's S2 round, findings 1, 3, 8 and 9. The containment hashes the Pi tree again through the descriptor it mounts, so a tree replaced after the attestation is refused; an install root anyone else could write, an entry another user owns and a file with a second name are refused. Links are followed link by link inside the tree (escapes, dangling links and cycles refused), in Go and the CI installer alike. Usage Pi did not give, or that cannot be counted or overflows, stays unknown however the run ends. The release check is tested marker by marker.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+531
−33
cmd/equipo-runner/release_guard_test.go+24 −0internal/fakepi/fake.go+7 −1internal/runner/containment/mounts.go+13 −0internal/runner/containment/pi_test.go+160 −0internal/runner/provider/check_policy.go+17 −0internal/runner/provider/pi/decode.go+63 −19internal/runner/provider/pi/decode_test.go+54 −2internal/runner/provider/pi/home.go+3 −0internal/runner/provider/pi/pins_test.go+40 −0internal/runner/provider/pi_policy_test.go+1 −0internal/runner/provider/tree.go+80 −6internal/runner/provider/tree_unix.go+26 −0internal/runner/thin/pistep_test.go+11 −0scripts/ci-box.py+32 −5
diff --git a/cmd/equipo-runner/release_guard_test.go b/cmd/equipo-runner/release_guard_test.go| index 4a67fafa..145e0789 100644 |
| --- a/cmd/equipo-runner/release_guard_test.go |
| +++ b/cmd/equipo-runner/release_guard_test.go |
| @@ -95,3 +95,27 @@ const spendMarker = "EQUIPO_TEST_LEAVE_TO_SPEND" |
| // egressMarker names the test build's egress route (internal/runner/egress |
| // proxy_testbuild.go). |
| const egressMarker = "EQUIPO_TEST_EGRESS_UPSTREAM" |
| + |
| +// The release check refuses each test-build marker on its own: a binary |
| +// that holds only one of them (and none of the others) is refused, and |
| +// one holding none is accepted. |
| +func TestReleaseCheckRefusesEachMarker(t *testing.T) { |
| + testci.Files(t, "../../scripts/no-fake-worker.sh") |
| + dir := t.TempDir() |
| + check := func(name, content string) error { |
| + path := filepath.Join(dir, name) |
| + if err := os.WriteFile(path, []byte("\x7fELF padding "+content+" padding"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err := exec.Command("../../scripts/no-fake-worker.sh", path).CombinedOutput() |
| + return err |
| + } |
| + if err := check("clean", "nothing of the test build"); err != nil { |
| + t.Fatalf("a clean binary was refused: %v", err) |
| + } |
| + for name, m := range map[string]string{"fake worker": marker, "egress route": egressMarker, "leave to spend": spendMarker} { |
| + if err := check(strings.ReplaceAll(name, " ", "-"), m); err == nil { |
| + t.Errorf("a binary with only the %s marker was accepted", name) |
| + } |
| + } |
| +} |
diff --git a/internal/fakepi/fake.go b/internal/fakepi/fake.go| index a62b9795..d103fbe3 100644 |
| --- a/internal/fakepi/fake.go |
| +++ b/internal/fakepi/fake.go |
| @@ -22,7 +22,7 @@ |
| // for each "review:changes:<path>|<line>|<text>"); "[Equipo: question]" |
| // 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, "sleep:<ms>" |
| +// 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 |
| // that answered, "unknown-event" emits a record of a type Equipo does |
| // not know. |
| @@ -286,6 +286,12 @@ func (f *fake) run(prompt string) { |
| f.send(map[string]any{"type": "auto_retry_end", "success": false, "attempt": 3, "finalError": "429"}) |
| f.send(map[string]any{"type": "agent_settled", "aborted": false}) |
| return |
| + case strings.Contains(prompt, "endnousage"): |
| + // The run ends properly, with no assistant message and so no usage. |
| + f.send(map[string]any{"type": "turn_end", "toolResults": []any{}}) |
| + f.send(map[string]any{"type": "agent_end", "messages": []any{}, "willRetry": false}) |
| + f.send(map[string]any{"type": "agent_settled", "aborted": false}) |
| + return |
| case strings.Contains(prompt, "nousage"): |
| // The process ends mid-run, with no message_end and no agent_end. |
| os.Exit(3) |
diff --git a/internal/runner/containment/mounts.go b/internal/runner/containment/mounts.go| index cf588734..ab83a27c 100644 |
| --- a/internal/runner/containment/mounts.go |
| +++ b/internal/runner/containment/mounts.go |
| @@ -242,6 +242,19 @@ func (m *Manager) mountPlan(l provider.Launch, dir string) (_ *mounts, err error |
| if err = p.bind(mount.Source, target, true, tree); err != nil { |
| return nil, err |
| } |
| + if l.Policy.IsPi() && target == provider.PiTree { |
| + // The tree as mounted, through the descriptor bubblewrap |
| + // mounts, not by its path again: one replaced after the |
| + // attestation is refused here. |
| + source, pin, ok := l.Policy.PiTree() |
| + mounted := p.files[len(p.files)-1] |
| + if !ok || source != mount.Source { |
| + return nil, errMount |
| + } |
| + if sum, err := provider.TreeSHA256(fmt.Sprintf("/proc/self/fd/%d/.", mounted.Fd())); err != nil || sum != pin { |
| + return nil, errMount |
| + } |
| + } |
| targets[target] = true |
| } |
| if l.ToolSocket != "" { |
diff --git a/internal/runner/containment/pi_test.go b/internal/runner/containment/pi_test.go| new file mode 100644 |
| index 00000000..7ff3029b |
| --- /dev/null |
| +++ b/internal/runner/containment/pi_test.go |
| @@ -0,0 +1,160 @@ |
| +package containment |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/testci" |
| +) |
| + |
| +// piLaunch is a Pi launch on m: a sealed package tree, the pinned files |
| +// (a copy of true stands in for Node), the runtime home under the |
| +// scratch root's homes, a key, a tool socket and a workspace. |
| +func piLaunch(t *testing.T, m *Manager) (provider.Launch, []string, string) { |
| + t.Helper() |
| + root := t.TempDir() |
| + put := func(name, content string, mode os.FileMode) string { |
| + p := filepath.Join(root, name) |
| + if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(p, []byte(content), mode); err != nil { |
| + t.Fatal(err) |
| + } |
| + return p |
| + } |
| + trueBin, err := os.ReadFile("/usr/bin/true") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + node := put("node", string(trueBin), 0755) |
| + tree := filepath.Join(root, "pi", "node_modules") |
| + put("pi/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli.js", "cli", 0644) |
| + put("pi/node_modules/dep/index.js", "dep", 0644) |
| + if err := provider.SealTree(tree); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { unsealTree(filepath.Dir(tree)) }) |
| + sum, err := provider.TreeSHA256(tree) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + home := filepath.Join(m.cfg.ScratchRoot, "homes", "pi-home") |
| + if err := os.MkdirAll(filepath.Join(home, "agent"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + os.Chmod(filepath.Join(m.cfg.ScratchRoot, "homes"), 0700) |
| + os.Chmod(home, 0700) |
| + work := filepath.Join(root, "work") |
| + os.Mkdir(work, 0700) |
| + keyHome := filepath.Join(root, "key") |
| + os.Mkdir(keyHome, 0700) |
| + put("key/"+provider.TokenFile, "tx-test-key", 0600) |
| + sockDir := filepath.Join(root, "tool") |
| + os.Mkdir(sockDir, 0700) |
| + ln, err := net.Listen("unix", filepath.Join(sockDir, "equipo.sock")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { ln.Close() }) |
| + os.Chmod(filepath.Join(sockDir, "equipo.sock"), 0600) |
| + nodeSum := sha256Hex(trueBin) |
| + in := provider.PiPolicyInputs{Node: node, NodeSHA256: nodeSum, Tree: tree, TreeSHA256: sum, Bwrap: "/usr/bin/bwrap", ToolProxy: put("proxy", "proxy", 0755), Extension: put("equipo.ts", "export default function () {}", 0600), |
| + Home: home, Workspace: work, Action: "inspect", Provider: "tensorx", Model: "z-ai/glm-5.3", KeyEnv: "TENSORX_API_KEY", Tools: []string{"read", "grep", "find", "ls", "mcp__equipo__submit_review"}, EgressHosts: []string{"api.tensorx.ai"}, |
| + Models: json.RawMessage(`{"providers":{"tensorx":{"api":"openai-completions","apiKey":"$TENSORX_API_KEY","baseUrl":"https://api.tensorx.ai/v1","models":[{"id":"z-ai/glm-5.3"}]}}}`), |
| + Settings: json.RawMessage(`{"defaultProjectTrust":"never"}`), |
| + MCP: json.RawMessage(`{"autoEnableCodemode":false,"mcpServers":{"equipo":{"args":["--socket","/tool/equipo.sock"],"command":"/opt/equipo-tool-proxy","exposure":"direct"}}}`)} |
| + if err := provider.WritePiConfig(in); err != nil { |
| + t.Fatal(err) |
| + } |
| + p, err := provider.BuildPiPolicy(in) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + l := provider.Launch{ToolSocket: filepath.Join(sockDir, "equipo.sock"), AttemptKey: "pi-swap", Workspace: work, Selection: provider.Selection{Provider: "tensorx", Model: "z-ai/glm-5.3"}, Binding: provider.PiBinding("tensorx-a", home, keyHome), Policy: p} |
| + return l, p.PiArgv(), tree |
| +} |
| + |
| +func unsealTree(dir string) { |
| + filepath.Walk(dir, func(p string, info os.FileInfo, err error) error { |
| + if err == nil && info.IsDir() { |
| + os.Chmod(p, 0755) |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +// A Pi launch mounts the very tree it hashed: replaced after the |
| +// attestation and before the mount (a file rewritten, or the whole |
| +// directory swapped at its path), the launch is refused; untouched, it |
| +// starts. |
| +func TestNamespacePiTreeSwapAfterAttestation(t *testing.T) { |
| + testci.Tools(t, "bwrap") |
| + for _, swap := range []string{"none", "file", "directory"} { |
| + t.Run(swap, func(t *testing.T) { |
| + m, _ := fixture(t) |
| + l, argv, tree := piLaunch(t, m) |
| + called := false |
| + m.beforePin = func() { |
| + called = true |
| + switch swap { |
| + case "file": |
| + f := filepath.Join(tree, "dep", "index.js") |
| + os.Chmod(filepath.Dir(f), 0755) |
| + os.Chmod(f, 0644) |
| + if err := os.WriteFile(f, []byte("changed"), 0644); err != nil { |
| + t.Fatal(err) |
| + } |
| + provider.SealTree(tree) |
| + case "directory": |
| + other := tree + "-other" |
| + if err := os.MkdirAll(filepath.Join(other, "dep"), 0755); err != nil { |
| + t.Fatal(err) |
| + } |
| + os.WriteFile(filepath.Join(other, "dep", "index.js"), []byte("other"), 0644) |
| + provider.SealTree(other) |
| + os.Chmod(filepath.Dir(tree), 0755) |
| + os.Chmod(tree, 0755) |
| + if err := os.Rename(tree, tree+"-old"); err != nil { |
| + t.Fatal(err) |
| + } |
| + os.Chmod(other, 0755) |
| + if err := os.Rename(other, tree); err != nil { |
| + t.Fatal(err) |
| + } |
| + os.Chmod(tree, 0555) |
| + } |
| + } |
| + p, err := m.Start(context.Background(), l, argv) |
| + if p != nil { |
| + p.(*process).kill() |
| + p.Wait(context.Background()) |
| + m.Stop(context.Background(), p.ID()) |
| + p.Stdin().Close() |
| + p.Stdout().Close() |
| + p.Stderr().Close() |
| + } |
| + if !called { |
| + t.Fatal("did not reach the attestation-to-mount boundary") |
| + } |
| + if swap == "none" && err != nil { |
| + t.Fatalf("the untouched tree was refused: %v", err) |
| + } |
| + if swap != "none" && err == nil { |
| + t.Fatal("a tree changed after its attestation was mounted") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func sha256Hex(raw []byte) string { |
| + sum := sha256.Sum256(raw) |
| + return hex.EncodeToString(sum[:]) |
| +} |
diff --git a/internal/runner/provider/check_policy.go b/internal/runner/provider/check_policy.go| index c2165073..000061b0 100644 |
| --- a/internal/runner/provider/check_policy.go |
| +++ b/internal/runner/provider/check_policy.go |
| @@ -365,6 +365,9 @@ func BuildPiPolicy(in PiPolicyInputs) (Policy, error) { |
| if m.Files[0].SHA256 != in.NodeSHA256 { |
| return Policy{}, ErrTree |
| } |
| + if err := TreeRootSafe(in.Tree); err != nil { |
| + return Policy{}, err |
| + } |
| tree, err := TreeSHA256(in.Tree) |
| if err != nil || tree != in.TreeSHA256 { |
| return Policy{}, ErrTree |
| @@ -435,6 +438,9 @@ func attestPi(l Launch, argv []string) (string, error) { |
| } |
| } |
| for _, t := range m.Trees { |
| + if err := TreeRootSafe(t.Mount.Source); err != nil { |
| + return "", err |
| + } |
| sum, err := TreeSHA256(t.Mount.Source) |
| if err != nil || sum != t.SHA256 { |
| return "", ErrTree |
| @@ -470,3 +476,14 @@ func (p Policy) PiArgv() []string { |
| } |
| return slices.Clone(m.Argv) |
| } |
| + |
| +// PiTree is a Pi policy's package tree: its source and pinned digest. |
| +// The containment hashes the tree again through the descriptor it |
| +// mounts, so what the namespace sees is what was pinned. |
| +func (p Policy) PiTree() (source, sha string, ok bool) { |
| + m, ok := piManifest(p) |
| + if !ok || len(m.Trees) != 1 { |
| + return "", "", false |
| + } |
| + return m.Trees[0].Mount.Source, m.Trees[0].SHA256, true |
| +} |
diff --git a/internal/runner/provider/pi/decode.go b/internal/runner/provider/pi/decode.go| index 4dc0e2be..cfb31e7d 100644 |
| --- a/internal/runner/provider/pi/decode.go |
| +++ b/internal/runner/provider/pi/decode.go |
| @@ -62,7 +62,11 @@ type ( |
| // Usage is one assistant message's usage as Pi reported it: input is |
| // already the uncached part. Cost is Pi's own figure in dollars, and |
| // Priced says Pi had one (from the provider or a configured price). |
| + // Valid is false when Pi gave no usage, or none that can be counted |
| + // (no input or output, a negative figure): the attempt's usage is |
| + // then unknown, never zero. |
| Usage struct { |
| + Valid bool `json:"valid"` |
| Model string `json:"model"` |
| Input int64 `json:"input"` |
| Output int64 `json:"output"` |
| @@ -139,20 +143,13 @@ func (d *Decoder) Decode(line []byte) ([]provider.Event, error) { |
| case "message_end": |
| var m struct { |
| Role, Model, StopReason, ErrorMessage string |
| - Usage struct { |
| - Input, Output, CacheRead, CacheWrite, Reasoning int64 |
| - Cost struct { |
| - Total float64 |
| - TotalFromProvider bool |
| - } |
| - } |
| + Usage json.RawMessage |
| } |
| if json.Unmarshal(r.Message, &m) != nil || m.Role != "assistant" { |
| return nil, nil |
| } |
| d.lastStop, d.lastError = m.StopReason, m.ErrorMessage |
| - u := m.Usage |
| - return event(KindUsage, Usage{Model: m.Model, Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.Reasoning, Cost: u.Cost.Total, Priced: u.Cost.TotalFromProvider || u.Cost.Total > 0}), nil |
| + 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 |
| case "tool_execution_end": |
| @@ -195,6 +192,34 @@ func (d *Decoder) Decode(line []byte) ([]provider.Event, error) { |
| return nil, nil |
| } |
| +// usageOf reads one message's usage: every figure Pi gave, and whether |
| +// it can be counted. |
| +func usageOf(model string, raw json.RawMessage) Usage { |
| + var u struct { |
| + Input, Output, CacheRead, CacheWrite, Reasoning *int64 |
| + Cost struct { |
| + Total float64 |
| + TotalFromProvider bool |
| + } |
| + } |
| + out := Usage{Model: model} |
| + if len(raw) == 0 || json.Unmarshal(raw, &u) != nil || u.Input == nil || u.Output == nil { |
| + return out |
| + } |
| + figure := func(v *int64) int64 { |
| + if v == nil { |
| + return 0 |
| + } |
| + return *v |
| + } |
| + out.Input, out.Output, out.CacheRead, out.CacheWrite, out.Reasoning = *u.Input, *u.Output, figure(u.CacheRead), figure(u.CacheWrite), figure(u.Reasoning) |
| + if out.Input < 0 || out.Output < 0 || out.CacheRead < 0 || out.CacheWrite < 0 || out.Reasoning < 0 || u.Cost.Total < 0 || math.IsNaN(u.Cost.Total) || math.IsInf(u.Cost.Total, 0) { |
| + return Usage{Model: model} |
| + } |
| + out.Cost, out.Priced, out.Valid = u.Cost.Total, u.Cost.TotalFromProvider || u.Cost.Total > 0, true |
| + return out |
| +} |
| + |
| // askTitle is the title Equipo's extension gives its question. |
| const askTitle = "equipo:tool_call" |
| @@ -230,35 +255,50 @@ func Family(model string) string { |
| // Tally sums an attempt's usage over its assistant messages (spec §2.3: |
| // Pi's message_end usage is per request). The row is complete once the |
| -// run's end was seen. |
| +// run's end was seen; its figures are unknown (null) when there was no |
| +// message, a message's usage could not be counted, or a sum overflowed. |
| type Tally struct { |
| model string |
| input, output, cacheRead, cacheWrite, thinking int64 |
| reported float64 |
| - priced bool |
| + priced, invalid bool |
| turns int64 |
| complete bool |
| } |
| +// add is a + b, or false when it overflows. |
| +func add(a, b int64) (int64, bool) { |
| + if b > 0 && a > math.MaxInt64-b { |
| + return 0, false |
| + } |
| + return a + b, true |
| +} |
| + |
| // Add takes one decoded event; only usage and done count. |
| func (t *Tally) Add(e provider.Event) { |
| switch e.Kind { |
| case KindUsage: |
| + t.turns++ |
| var u Usage |
| - if json.Unmarshal(e.Payload, &u) != nil { |
| + if json.Unmarshal(e.Payload, &u) != nil || !u.Valid { |
| + t.invalid = true |
| return |
| } |
| if t.model == "" { |
| t.model = u.Model |
| } |
| - t.input += u.Input |
| - t.output += u.Output |
| - t.cacheRead += u.CacheRead |
| - t.cacheWrite += u.CacheWrite |
| - t.thinking += u.Reasoning |
| + for _, p := range []struct { |
| + sum *int64 |
| + v int64 |
| + }{{&t.input, u.Input}, {&t.output, u.Output}, {&t.cacheRead, u.CacheRead}, {&t.cacheWrite, u.CacheWrite}, {&t.thinking, u.Reasoning}} { |
| + v, ok := add(*p.sum, p.v) |
| + if !ok { |
| + t.invalid = true |
| + } |
| + *p.sum = v |
| + } |
| t.reported += u.Cost |
| t.priced = t.priced || u.Priced |
| - t.turns++ |
| case KindDone: |
| t.complete = true |
| } |
| @@ -271,7 +311,11 @@ func (t *Tally) Model() string { return t.model } |
| // the caller's). |
| func (t *Tally) Row() wire.Usage { |
| v := func(n int64) *int64 { return &n } |
| - row := wire.Usage{Model: t.model, Complete: t.complete, InputTokens: v(t.input), OutputTokens: v(t.output), CachedInputTokens: v(t.cacheRead), CacheWriteTokens: v(t.cacheWrite), ReasoningOutputTokens: v(t.thinking), Turns: v(t.turns)} |
| + row := wire.Usage{Model: t.model, Complete: t.complete, Turns: v(t.turns)} |
| + if t.invalid || t.turns == 0 { |
| + return row |
| + } |
| + row.InputTokens, row.OutputTokens, row.CachedInputTokens, row.CacheWriteTokens, row.ReasoningOutputTokens = v(t.input), v(t.output), v(t.cacheRead), v(t.cacheWrite), v(t.thinking) |
| if t.priced && t.reported >= 0 && t.reported < math.MaxInt64/1e6 { |
| row.CostReportedMicros = v(int64(math.Ceil(t.reported*1e6 - 1e-9))) |
| } |
diff --git a/internal/runner/provider/pi/decode_test.go b/internal/runner/provider/pi/decode_test.go| index b30814c4..7083da42 100644 |
| --- a/internal/runner/provider/pi/decode_test.go |
| +++ b/internal/runner/provider/pi/decode_test.go |
| @@ -172,8 +172,8 @@ func TestTallyUsage(t *testing.T) { |
| t.Fatalf("turns %d", *row.Turns) |
| } |
| priced := &Tally{} |
| - priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"model":"m","input":10,"output":2,"cost":0.0123456,"priced":true}`)}) |
| - priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"model":"m","input":10,"output":2,"cost":0.0000001,"priced":true}`)}) |
| + priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"m","input":10,"output":2,"cost":0.0123456,"priced":true}`)}) |
| + priced.Add(provider.Event{Kind: KindUsage, Payload: json.RawMessage(`{"valid":true,"model":"m","input":10,"output":2,"cost":0.0000001,"priced":true}`)}) |
| priced.Add(provider.Event{Kind: KindDone, Payload: json.RawMessage(`{"status":"completed"}`)}) |
| if r := priced.Row(); r.CostReportedMicros == nil || *r.CostReportedMicros != 12346 { |
| t.Fatalf("reported %v", r.CostReportedMicros) |
| @@ -193,3 +193,55 @@ func TestFamilyFromModel(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// Usage Pi did not give, or gave in a shape that cannot be counted, |
| +// stays unknown even when the run ends properly: no message's usage at |
| +// all, a message without its usage or without input or output, a |
| +// negative figure, a sum that overflows. Unknown is never zero. |
| +func TestTallyUnknownUsage(t *testing.T) { |
| + end := `{"type":"agent_end","willRetry":false}` |
| + msg := func(usage string) string { |
| + return `{"type":"message_end","message":{"role":"assistant","model":"m","stopReason":"stop"` + usage + `}}` |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + lines []string |
| + }{ |
| + {"no message at all", []string{end}}, |
| + {"a message without usage", []string{msg(``), end}}, |
| + {"usage without input", []string{msg(`,"usage":{"output":3}`), end}}, |
| + {"usage without output", []string{msg(`,"usage":{"input":3}`), end}}, |
| + {"a negative figure", []string{msg(`,"usage":{"input":-1,"output":3}`), end}}, |
| + {"usage that is not an object", []string{msg(`,"usage":"lots"`), end}}, |
| + {"one good message, one without usage", []string{msg(`,"usage":{"input":3,"output":3}`), msg(``), end}}, |
| + {"a sum that overflows", []string{msg(`,"usage":{"input":9223372036854775807,"output":1}`), msg(`,"usage":{"input":1,"output":1}`), end}}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + d, tally := &Decoder{}, &Tally{} |
| + for _, line := range tc.lines { |
| + evs, err := d.Decode([]byte(line)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, e := range evs { |
| + tally.Add(e) |
| + } |
| + } |
| + row := tally.Row() |
| + if row.InputTokens != nil || row.OutputTokens != nil { |
| + t.Fatalf("unknown usage counted: in %v out %v complete %v", row.InputTokens, row.OutputTokens, row.Complete) |
| + } |
| + }) |
| + } |
| + // Zero usage Pi reported (a refused request) is a known zero. |
| + d, tally := &Decoder{}, &Tally{} |
| + for _, line := range []string{msg(`,"usage":{"input":0,"output":0,"cacheRead":0,"cacheWrite":0}`), end} { |
| + evs, _ := d.Decode([]byte(line)) |
| + for _, e := range evs { |
| + tally.Add(e) |
| + } |
| + } |
| + if row := tally.Row(); row.InputTokens == nil || *row.InputTokens != 0 || !row.Complete { |
| + t.Fatalf("a reported zero: %+v", row) |
| + } |
| +} |
diff --git a/internal/runner/provider/pi/home.go b/internal/runner/provider/pi/home.go| index eb0b9328..3df1c82c 100644 |
| --- a/internal/runner/provider/pi/home.go |
| +++ b/internal/runner/provider/pi/home.go |
| @@ -198,6 +198,9 @@ func Verify(root string) error { |
| if hex.EncodeToString(sum[:]) != nodePin.BinarySHA256 { |
| return ErrUnpinned |
| } |
| + if provider.TreeRootSafe(tree) != nil { |
| + return ErrUnpinned |
| + } |
| got, err := TreeSHA256(tree) |
| if err != nil || got != treePin { |
| return ErrUnpinned |
diff --git a/internal/runner/provider/pi/pins_test.go b/internal/runner/provider/pi/pins_test.go| index accdad6c..8d98f3a4 100644 |
| --- a/internal/runner/provider/pi/pins_test.go |
| +++ b/internal/runner/provider/pi/pins_test.go |
| @@ -102,6 +102,46 @@ func TestTreeDigest(t *testing.T) { |
| return err |
| }, true}, |
| {"writable file", func(d string) error { return os.Chmod(filepath.Join(d, "a/index.js"), 0644) }, true}, |
| + // Containment is resolved, not lexical: b's text stays inside, but |
| + // through the link a it leaves the tree. |
| + {"a chain out of the tree", func(d string) error { |
| + os.Chmod(d, 0755) |
| + defer os.Chmod(d, 0555) |
| + for _, dir := range []string{"sub", "real"} { |
| + if err := os.Mkdir(filepath.Join(d, dir), 0555); err != nil { |
| + return err |
| + } |
| + } |
| + os.Chmod(filepath.Join(d, "sub"), 0755) |
| + defer os.Chmod(filepath.Join(d, "sub"), 0555) |
| + if err := os.Symlink("../real", filepath.Join(d, "sub/a")); err != nil { |
| + return err |
| + } |
| + return os.Symlink("a/../../outside", filepath.Join(d, "sub/b")) |
| + }, true}, |
| + {"a dangling link", func(d string) error { |
| + os.Chmod(d, 0755) |
| + defer os.Chmod(d, 0555) |
| + return os.Symlink("a/missing.js", filepath.Join(d, "gone")) |
| + }, true}, |
| + {"a cycle", func(d string) error { |
| + os.Chmod(d, 0755) |
| + defer os.Chmod(d, 0555) |
| + if err := os.Symlink("y", filepath.Join(d, "x")); err != nil { |
| + return err |
| + } |
| + return os.Symlink("x", filepath.Join(d, "y")) |
| + }, true}, |
| + {"a link to a directory inside", func(d string) error { |
| + os.Chmod(d, 0755) |
| + defer os.Chmod(d, 0555) |
| + return os.Symlink("a/bin", filepath.Join(d, "bin-link")) |
| + }, false}, |
| + {"a second name for a file", func(d string) error { |
| + os.Chmod(d, 0755) |
| + defer os.Chmod(d, 0555) |
| + return os.Link(filepath.Join(d, "a/index.js"), filepath.Join(d, "alias.js")) |
| + }, true}, |
| {"writable directory", func(d string) error { return os.Chmod(filepath.Join(d, "a"), 0755) }, true}, |
| } { |
| t.Run(tc.name, func(t *testing.T) { |
diff --git a/internal/runner/provider/pi_policy_test.go b/internal/runner/provider/pi_policy_test.go| index acaae15c..8fd80bfd 100644 |
| --- a/internal/runner/provider/pi_policy_test.go |
| +++ b/internal/runner/provider/pi_policy_test.go |
| @@ -148,6 +148,7 @@ func TestPiPolicyRefusals(t *testing.T) { |
| {"another node", "inspect", reviewTools, func(in *PiPolicyInputs) { in.NodeSHA256 = digest([]byte("other")) }}, |
| {"another tree", "inspect", reviewTools, func(in *PiPolicyInputs) { in.TreeSHA256 = digest([]byte("other")) }}, |
| {"a writable tree", "inspect", reviewTools, func(in *PiPolicyInputs) { os.Chmod(in.Tree, 0755) }}, |
| + {"an install root others can write", "inspect", reviewTools, func(in *PiPolicyInputs) { os.Chmod(filepath.Dir(in.Tree), 0777) }}, |
| {"a key variable of another name", "inspect", reviewTools, func(in *PiPolicyInputs) { in.KeyEnv = "OPENAI_API_KEY" }}, |
| {"a test CA in a release build", "inspect", reviewTools, func(in *PiPolicyInputs) { in.ExtraCA = in.Bwrap }}, |
| } { |
diff --git a/internal/runner/provider/tree.go b/internal/runner/provider/tree.go| index 384d624a..8bb40fb4 100644 |
| --- a/internal/runner/provider/tree.go |
| +++ b/internal/runner/provider/tree.go |
| @@ -60,9 +60,11 @@ func SealTree(dir string) error { |
| // TreeSHA256 names an installed tree by every entry, in walk order: a |
| // directory by its path, a file by its path, mode and SHA-256, a link by |
| -// its path and target. A link must be relative and resolve inside the |
| -// tree; anything writable, any absolute or escaping link and any other |
| -// kind of entry is refused. |
| +// its path and target. A link must be relative and, followed link by |
| +// link, resolve to an entry inside the tree; anything writable, a file |
| +// with a second name (a hard link another path could write through), any |
| +// absolute, escaping, dangling or cyclic link and any other kind of entry |
| +// is refused. dir may be a retained descriptor's path (/proc/self/fd/N/.). |
| func TreeSHA256(dir string) (string, error) { |
| h := sha256.New() |
| err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { |
| @@ -75,6 +77,9 @@ func TreeSHA256(dir string) (string, error) { |
| } |
| rel, _ := filepath.Rel(dir, path) |
| rel = filepath.ToSlash(rel) |
| + if info.Mode()&fs.ModeSymlink == 0 && !ownedHere(info) { |
| + return ErrTree |
| + } |
| switch { |
| case d.IsDir(): |
| if info.Mode().Perm()&0222 != 0 { |
| @@ -82,7 +87,7 @@ func TreeSHA256(dir string) (string, error) { |
| } |
| fmt.Fprintf(h, "d\x00%s\x00%o\n", rel, info.Mode().Perm()) |
| case info.Mode().IsRegular(): |
| - if info.Mode().Perm()&0222 != 0 { |
| + if info.Mode().Perm()&0222 != 0 || !singleLink(info) { |
| return ErrTree |
| } |
| sum, err := treeFileSHA256(path) |
| @@ -95,8 +100,7 @@ func TreeSHA256(dir string) (string, error) { |
| if err != nil { |
| return err |
| } |
| - resolved := filepath.Join(filepath.Dir(path), target) |
| - if filepath.IsAbs(target) || !strings.HasPrefix(resolved, dir+string(filepath.Separator)) { |
| + if filepath.IsAbs(target) || resolveInside(dir, rel) != nil { |
| return ErrTree |
| } |
| fmt.Fprintf(h, "l\x00%s\x00%s\n", rel, filepath.ToSlash(target)) |
| @@ -111,6 +115,51 @@ func TreeSHA256(dir string) (string, error) { |
| return hex.EncodeToString(h.Sum(nil)), nil |
| } |
| +// maxLinkHops bounds a chain of links (as the kernel's own limit does). |
| +const maxLinkHops = 40 |
| + |
| +// resolveInside follows the entry at rel (relative to root) component by |
| +// component, each link's target taken from where the link is, and |
| +// refuses a path that climbs above root, an entry that does not exist, |
| +// an absolute target and a chain longer than maxLinkHops (a cycle). |
| +func resolveInside(root, rel string) error { |
| + var cur []string |
| + queue := strings.Split(filepath.ToSlash(rel), "/") |
| + hops := 0 |
| + for len(queue) > 0 { |
| + c := queue[0] |
| + queue = queue[1:] |
| + switch c { |
| + case "", ".": |
| + continue |
| + case "..": |
| + if len(cur) == 0 { |
| + return ErrTree |
| + } |
| + cur = cur[:len(cur)-1] |
| + continue |
| + } |
| + next := append(append([]string(nil), cur...), c) |
| + info, err := os.Lstat(filepath.Join(append([]string{root}, next...)...)) |
| + if err != nil { |
| + return ErrTree |
| + } |
| + if info.Mode()&fs.ModeSymlink == 0 { |
| + cur = next |
| + continue |
| + } |
| + if hops++; hops > maxLinkHops { |
| + return ErrTree |
| + } |
| + target, err := os.Readlink(filepath.Join(append([]string{root}, next...)...)) |
| + if err != nil || filepath.IsAbs(target) { |
| + return ErrTree |
| + } |
| + queue = append(strings.Split(filepath.ToSlash(target), "/"), queue...) |
| + } |
| + return nil |
| +} |
| + |
| func treeFileSHA256(path string) (string, error) { |
| f, err := os.Open(path) |
| if err != nil { |
| @@ -123,3 +172,28 @@ func treeFileSHA256(path string) (string, error) { |
| } |
| return hex.EncodeToString(h.Sum(nil)), nil |
| } |
| + |
| +// TreeRootSafe refuses a tree that someone other than this user (or |
| +// root) could replace: every directory from / down to it must be a real |
| +// directory (no link on the way), owned by root or this user, and |
| +// writable by nobody else unless sticky (as /tmp is, where nobody may |
| +// rename another's entry). Group write is allowed only for this user's |
| +// own group (a user private group, Debian's default). |
| +func TreeRootSafe(path string) error { |
| + if !filepath.IsAbs(path) || filepath.Clean(path) != path { |
| + return ErrTree |
| + } |
| + for dir := path; ; dir = filepath.Dir(dir) { |
| + info, err := os.Lstat(dir) |
| + if err != nil || !info.IsDir() || !ownedHere(info) { |
| + return ErrTree |
| + } |
| + writable := info.Mode().Perm()&0002 != 0 || info.Mode().Perm()&0020 != 0 && !ownGroup(info) |
| + if writable && info.Mode()&fs.ModeSticky == 0 { |
| + return ErrTree |
| + } |
| + if dir == "/" { |
| + return nil |
| + } |
| + } |
| +} |
diff --git a/internal/runner/provider/tree_unix.go b/internal/runner/provider/tree_unix.go| new file mode 100644 |
| index 00000000..5dca11be |
| --- /dev/null |
| +++ b/internal/runner/provider/tree_unix.go |
| @@ -0,0 +1,26 @@ |
| +//go:build unix |
| + |
| +package provider |
| + |
| +import ( |
| + "os" |
| + "syscall" |
| +) |
| + |
| +// singleLink reports whether a file has one name only. |
| +func singleLink(info os.FileInfo) bool { |
| + st, ok := info.Sys().(*syscall.Stat_t) |
| + return ok && st.Nlink == 1 |
| +} |
| + |
| +// ownedHere reports whether root or this user owns an entry. |
| +func ownedHere(info os.FileInfo) bool { |
| + st, ok := info.Sys().(*syscall.Stat_t) |
| + return ok && (st.Uid == 0 || int(st.Uid) == os.Geteuid()) |
| +} |
| + |
| +// ownGroup reports whether an entry's group is this user's own. |
| +func ownGroup(info os.FileInfo) bool { |
| + st, ok := info.Sys().(*syscall.Stat_t) |
| + return ok && int(st.Gid) == os.Getegid() |
| +} |
diff --git a/internal/runner/thin/pistep_test.go b/internal/runner/thin/pistep_test.go| index a4ef4536..056b2783 100644 |
| --- a/internal/runner/thin/pistep_test.go |
| +++ b/internal/runner/thin/pistep_test.go |
| @@ -470,3 +470,14 @@ func TestPiEngineeringHeldIsDeferred(t *testing.T) { |
| t.Fatalf("report %+v, charges %d", rep, r.charges()) |
| } |
| } |
| + |
| +// A run that ends properly (agent_end) with no usage figure is unknown |
| +// spend too, never a charge of zero. |
| +func TestPiEndWithoutUsagePausesTheConnection(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + leave(t) |
| + r.runReview("endnousage", 1) |
| + if !r.conn().SpendUnknown || !r.slotFree() { |
| + t.Fatalf("spend unknown %v, slot free %v", r.conn().SpendUnknown, r.slotFree()) |
| + } |
| +} |
diff --git a/scripts/ci-box.py b/scripts/ci-box.py| index 62020fb7..f06eb20c 100755 |
| --- a/scripts/ci-box.py |
| +++ b/scripts/ci-box.py |
| @@ -269,13 +269,40 @@ def tree_sha256(top): |
| def mode(st): |
| return format(st.st_mode & 0o777, "o") |
| + def resolve_inside(rel): |
| + """provider.resolveInside: follow the entry link by link, each |
| + target from where its link is; never above the tree, never to |
| + nothing, at most 40 links.""" |
| + cur, queue, hops = [], rel.split("/"), 0 |
| + while queue: |
| + c = queue.pop(0) |
| + if c in ("", "."): |
| + continue |
| + if c == "..": |
| + if not cur: |
| + raise RuntimeError("pi tree: link %s leaves the tree" % rel) |
| + cur.pop() |
| + continue |
| + nxt = cur + [c] |
| + p = os.path.join(top, *nxt) |
| + if not os.path.lexists(p): |
| + raise RuntimeError("pi tree: link %s leads to nothing" % rel) |
| + if not os.path.islink(p): |
| + cur = nxt |
| + continue |
| + hops += 1 |
| + target = os.readlink(p) |
| + if hops > 40 or os.path.isabs(target): |
| + raise RuntimeError("pi tree: link %s loops or is absolute" % rel) |
| + queue = target.split("/") + queue |
| + |
| def visit(path, rel): |
| st = os.lstat(path) |
| if os.path.islink(path): |
| target = os.readlink(path) |
| - resolved = os.path.normpath(os.path.join(os.path.dirname(path), target)) |
| - if os.path.isabs(target) or not resolved.startswith(top + os.sep): |
| - raise RuntimeError("pi tree: link %s leaves the tree" % rel) |
| + if os.path.isabs(target): |
| + raise RuntimeError("pi tree: link %s is absolute" % rel) |
| + resolve_inside(rel) |
| h.update(("l\0%s\0%s\n" % (rel, target)).encode()) |
| return |
| if st.st_mode & 0o222: |
| @@ -285,8 +312,8 @@ def tree_sha256(top): |
| for name in sorted(os.listdir(path)): |
| visit(os.path.join(path, name), name if rel == "." else rel + "/" + name) |
| return |
| - if not os.path.isfile(path): |
| - raise RuntimeError("pi tree: %s is not a file" % rel) |
| + if not os.path.isfile(path) or st.st_nlink != 1: |
| + raise RuntimeError("pi tree: %s is not a file with one name" % rel) |
| h.update(("f\0%s\0%s\0%s\n" % (rel, mode(st), sha256_file(path))).encode()) |
| visit(top, ".") |