From aa632451a6907ab8c7f6b0c76edbfaa4cf196a22 Mon Sep 17 00:00:00 2001 From: zhoushoujian Date: Thu, 19 Nov 2026 14:52:44 +0800 Subject: [PATCH] fix(execution): support native Codex app-server images --- docs/execution-pkg-detail.md | 25 +- docs/execution-pkg.md | 7 +- internal/worker/codex_app_server.go | 19 +- .../worker/codex_app_server_image_test.go | 231 ++++++++++++++++++ internal/worker/codex_host_test.go | 14 +- internal/worker/image_redaction.go | 152 ++++++++++++ internal/worker/image_redaction_test.go | 219 +++++++++++++++++ internal/worker/native_controls.go | 7 +- internal/worker/output.go | 101 +++++--- 9 files changed, 725 insertions(+), 50 deletions(-) create mode 100644 internal/worker/codex_app_server_image_test.go create mode 100644 internal/worker/image_redaction.go create mode 100644 internal/worker/image_redaction_test.go diff --git a/docs/execution-pkg-detail.md b/docs/execution-pkg-detail.md index a8abb2e..61de692 100644 --- a/docs/execution-pkg-detail.md +++ b/docs/execution-pkg-detail.md @@ -150,16 +150,20 @@ explicitly in `config.skills.config` for both thread start and resume; arbitrary native config-file contents are never forwarded. Unsupported writes, malformed responses and state mismatches fail closed without starting or resuming a thread. Ambient apps, cloud and bundled Skills, plugins, project instructions and MCP -configuration are replaced by the explicit request configuration. Images, -forks, tool-free execution, +configuration are replaced by the explicit request configuration. Up to four +validated images are sent inline after the task text, in caller order; optional +names are separate safely quoted text items. Forks, tool-free execution, extraction, restricted reads and tool allowlists remain unsupported on this path. App-server raw callbacks carry `NativeProtocol="codex-app-server"` and preserve -the original JSON-RPC method and params. Matching thread/turn completion is the -only success terminal. Model evidence comes from thread start/resume and native -reroute notifications; missing model, usage and cost remain unavailable. On -cancellation Offload first requests `turn/interrupt`, then closes and reaps the -same owned process group under the normal worker bounds. +protocol metadata. Returned image data-URL payloads are replaced, before parsing +or retention, by their digest and byte count; malformed or oversized image-bearing +frames become bounded omission records. This applies to observers, transcript +captures, diagnostics and fresh or resumed history results. Matching thread/turn +completion is the only success terminal. Model evidence comes from thread +start/resume and native reroute notifications; missing model, usage and cost remain +unavailable. On cancellation Offload first requests `turn/interrupt`, then closes +and reaps the same owned process group under the normal worker bounds. The initialize request opts into the experimental API required by explicit Skill roots. Native app-server responses may omit the optional `jsonrpc` member; an explicit version other than `2.0` is rejected. @@ -167,9 +171,10 @@ Completed agent-message items are authoritative final text when deltas or termin turn items are absent. Malformed response envelopes fail before dispatch, and a failed turn retains only a bounded single-line provider diagnostic. -For Native calls, callbacks retain complete events up to 32 MiB (bounded image -envelopes included), including a final unterminated line. Larger events fail -explicitly. The default 256 KiB callback contract is unchanged for other callers. +For Native calls, callbacks retain complete events up to 32 MiB (with Codex +app-server image payloads redacted first), including a final unterminated line. +Larger events fail explicitly. The default 256 KiB callback contract is unchanged +for other callers. After process exit, idle pipe reads are bounded independently of callback time. Native caller-context cancellation freezes and stops the owned descendant tree, including native Bash children in separate sessions; it never selects by command diff --git a/docs/execution-pkg.md b/docs/execution-pkg.md index b2d4692..b98f229 100644 --- a/docs/execution-pkg.md +++ b/docs/execution-pkg.md @@ -69,9 +69,10 @@ a normalized or complete UI transcript. Optional `Request.Native` controls let an embedding Host preserve Claude session IDs/forks, exact MCP and Skills mounts, permissions, structured extraction and -image input through the same worker. `CallerContext` keeps caller-supplied -instructions and task separate from Offload's delegation role. Set `Caller` and -`CallerRunID` on business and internal requests so history keeps attribution. +image input through the same worker. Codex image input requires its explicit +app-server mode; legacy Codex execution still rejects it. `CallerContext` keeps +caller-supplied instructions and task separate from Offload's delegation role. +Set `Caller` and `CallerRunID` on business and internal requests so history keeps attribution. Unsupported backend controls fail before launch; ordinary Codex requests remain supported. This adds no Host policy, message routing or automatic session adoption. diff --git a/internal/worker/codex_app_server.go b/internal/worker/codex_app_server.go index 1502695..6275545 100644 --- a/internal/worker/codex_app_server.go +++ b/internal/worker/codex_app_server.go @@ -1,6 +1,7 @@ package worker import ( + "encoding/base64" "encoding/json" "errors" "fmt" @@ -18,6 +19,8 @@ import ( const codexAppServerProtocol = "codex-app-server" +const codexAppServerMaxFrame = 32 << 20 + type appServerMessage struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id"` @@ -227,7 +230,7 @@ func (p *appServerParser) write(v any) error { if err != nil { return err } - if len(b) > maxLineKept { + if len(b) > codexAppServerMaxFrame { return errors.New("Codex app-server request exceeds frame limit") } b = append(b, '\n') @@ -304,7 +307,7 @@ func (p *appServerParser) initialize() error { p.threadID, p.s.Session = thread.Thread.ID, thread.Thread.ID p.s.ObservedModel = firstNonEmpty(thread.Model, thread.Thread.Model) p.mu.Unlock() - turn := map[string]any{"threadId": thread.Thread.ID, "input": []any{map[string]any{"type": "text", "text": p.o.Task}}, "cwd": p.o.Dir, "runtimeWorkspaceRoots": roots} + turn := appServerTurnParams(p.o, thread.Thread.ID, roots) if p.o.Native.JSONSchema != "" { var schema any _ = json.Unmarshal([]byte(p.o.Native.JSONSchema), &schema) @@ -328,6 +331,18 @@ func (p *appServerParser) initialize() error { return nil } +func appServerTurnParams(o Opts, threadID string, roots []string) map[string]any { + input := []any{map[string]any{"type": "text", "text": o.Task}} + for _, image := range o.Native.Images { + if image.Name != "" { + name, _ := json.Marshal(image.Name) + input = append(input, map[string]any{"type": "text", "text": "Image name: " + string(name)}) + } + input = append(input, map[string]any{"type": "image", "url": "data:" + image.MediaType + ";base64," + base64.StdEncoding.EncodeToString(image.Data)}) + } + return map[string]any{"threadId": threadID, "input": input, "cwd": o.Dir, "runtimeWorkspaceRoots": roots} +} + func (p *appServerParser) initializeExactSkills() error { manifest, err := exactSkillManifest(p.o.Native.SkillRoots) if err != nil { diff --git a/internal/worker/codex_app_server_image_test.go b/internal/worker/codex_app_server_image_test.go new file mode 100644 index 0000000..7408b69 --- /dev/null +++ b/internal/worker/codex_app_server_image_test.go @@ -0,0 +1,231 @@ +package worker + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" +) + +type imageRecordingCapture struct{ lines []string } + +func (*imageRecordingCapture) AddSecrets(...string) {} +func (*imageRecordingCapture) BeginAttempt(string, string) {} +func (c *imageRecordingCapture) Line(line []byte) { + c.lines = append(c.lines, string(line)) +} +func (*imageRecordingCapture) Skipped(string, int) {} + +func TestCodexAppServerTurnCarriesOrderedImagesOnFreshAndResume(t *testing.T) { + images := []NativeImage{ + {Name: "first \"label\".png", MediaType: "image/png", Data: []byte{0, 1, 2, 3}}, + {MediaType: "image/webp", Data: []byte("exact second image")}, + } + for _, resume := range []bool{false, true} { + name := "fresh" + if resume { + name = "resume" + } + t.Run(name, func(t *testing.T) { + bin, log := appServerFixture(t, "", completedAppServerTail) + o := appServerOpts(t, t.TempDir()) + o.Native.SkillRoots, o.Native.JSONSchema, o.Native.Images = nil, "", images + if resume { + o.Resume = "existing-thread" + } + a := runAttempt(context.Background(), bin, o, "", "", o.Timeout, nil, hooks{}) + if a.runErr != nil || a.s.Result == nil { + t.Fatalf("%+v", a) + } + input := capturedTurnInput(t, log) + if len(input) != 4 || input[0].Type != "text" || input[0].Text != o.Task || input[1].Type != "text" || input[1].Text != `Image name: "first \"label\".png"` { + t.Fatalf("unexpected ordered input: %+v", input) + } + for index, position := range []int{2, 3} { + got := input[position] + want := images[index] + prefix := "data:" + want.MediaType + ";base64," + if got.Type != "image" || !strings.HasPrefix(got.URL, prefix) || strings.Contains(got.URL, "http://") || strings.Contains(got.URL, "https://") { + t.Fatalf("image %d was not inline: %+v", index, got) + } + decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(got.URL, prefix)) + if err != nil || string(decoded) != string(want.Data) { + t.Fatalf("image %d bytes changed: %x %v", index, decoded, err) + } + } + }) + } +} + +type capturedUserInput struct { + Type string `json:"type"` + Text string `json:"text"` + URL string `json:"url"` +} + +func capturedTurnInput(t *testing.T, path string) []capturedUserInput { + t.Helper() + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(string(raw), "\n") { + var request struct { + Method string `json:"method"` + Params struct { + Input []capturedUserInput `json:"input"` + } `json:"params"` + } + if json.Unmarshal([]byte(line), &request) == nil && request.Method == "turn/start" { + return request.Params.Input + } + } + t.Fatalf("turn/start missing from %s", raw) + return nil +} + +func TestCodexImageValidationPreservesBoundsAndLegacyRejection(t *testing.T) { + valid := NativeImage{Name: "image.png", MediaType: "image/png", Data: []byte("x")} + base := NativeControls{CallerContext: true, CodexAppServer: true, PermissionMode: "bypassPermissions"} + for _, tc := range []struct { + name string + change func(*NativeControls) + }{ + {name: "too many", change: func(n *NativeControls) { n.Images = []NativeImage{valid, valid, valid, valid, valid} }}, + {name: "too large", change: func(n *NativeControls) { + n.Images = []NativeImage{{MediaType: "image/png", Data: make([]byte, (5<<20)+1)}} + }}, + {name: "unsupported MIME", change: func(n *NativeControls) { n.Images = []NativeImage{{MediaType: "image/svg+xml", Data: []byte("x")}} }}, + {name: "invalid name", change: func(n *NativeControls) { + n.Images = []NativeImage{{Name: string([]byte{0xff}), MediaType: "image/png", Data: []byte("x")}} + }}, + {name: "legacy", change: func(n *NativeControls) { n.CodexAppServer = false; n.Images = []NativeImage{valid} }}, + } { + t.Run(tc.name, func(t *testing.T) { + n := base + tc.change(&n) + if err := n.Validate("codex", "", false); err == nil { + t.Fatal("invalid image controls accepted") + } + }) + } +} + +func TestCodexAppServerMaximalValidImagesFitOutboundFrame(t *testing.T) { + data := bytes.Repeat([]byte{0xa5}, 5<<20) + images := make([]NativeImage, 4) + for i := range images { + images[i] = NativeImage{MediaType: "image/png", Data: data} + } + o := Opts{Task: "maximal images", Dir: "/workspace", Native: &NativeControls{Images: images}} + params := appServerTurnParams(o, "thread-max", []string{"/workspace"}) + var output bytes.Buffer + parser := newAppServerParser(discardWriteCloser{&output}, o) + if err := parser.write(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "turn/start", "params": params}); err != nil { + t.Fatal(err) + } + if output.Len() <= maxLineKept || output.Len() > codexAppServerMaxFrame+1 { + t.Fatalf("serialized frame size=%d, want (%d,%d]", output.Len(), maxLineKept, codexAppServerMaxFrame+1) + } + var request struct { + Method string `json:"method"` + Params struct { + Input []capturedUserInput `json:"input"` + } `json:"params"` + } + if err := json.Unmarshal(bytes.TrimSpace(output.Bytes()), &request); err != nil || request.Method != "turn/start" || len(request.Params.Input) != 5 { + t.Fatalf("invalid maximal turn request: method=%q input=%d err=%v", request.Method, len(request.Params.Input), err) + } + for index, item := range request.Params.Input[1:] { + payload := strings.TrimPrefix(item.URL, "data:image/png;base64,") + decoded, err := base64.StdEncoding.DecodeString(payload) + if item.Type != "image" || err != nil || !bytes.Equal(decoded, data) { + t.Fatalf("image %d did not round trip: type=%q bytes=%d err=%v", index, item.Type, len(decoded), err) + } + } +} + +func TestCodexAppServerRedactsImageFromRecordObserverAndTranscript(t *testing.T) { + root := t.TempDir() + skill := filepath.Join(root, "SKILL.md") + if err := os.WriteFile(skill, []byte("fixture"), 0600); err != nil { + t.Fatal(err) + } + secret := []byte("history-private-image-bytes") + dataURL := "data:image/png;base64," + base64.StdEncoding.EncodeToString(secret) + nested, err := json.Marshal(map[string]any{"type": "image", "url": dataURL}) + if err != nil { + t.Fatal(err) + } + turnStarted := mustTestJSON(t, map[string]any{ + "method": "turn/started", + "params": map[string]any{"threadId": "thread-native", "turn": map[string]any{"id": "turn-native"}}, + }) + started := mustTestJSON(t, map[string]any{ + "method": "item/started", + "params": map[string]any{ + "threadId": "thread-native", "turnId": "turn-native", + "item": map[string]any{"id": "user", "type": "userMessage", "content": []any{map[string]any{"type": "image", "url": dataURL}}}, + }, + }) + completed := mustTestJSON(t, map[string]any{ + "method": "item/completed", + "params": map[string]any{ + "threadId": "thread-native", "turnId": "turn-native", + "item": map[string]any{"id": "answer", "type": "agentMessage", "text": string(nested)}, + }, + }) + turnCompleted := mustTestJSON(t, map[string]any{ + "method": "turn/completed", + "params": map[string]any{ + "threadId": "thread-native", + "turn": map[string]any{"id": "turn-native", "status": "completed", "items": []any{}, "error": nil}, + }, + }) + tail := fmt.Sprintf("printf '%%s\\n' '%s'\nprintf '%%s\\n' '%s'\nprintf '%%s\\n' '%s'\nprintf '%%s\\n' '%s'", turnStarted, started, completed, turnCompleted) + bin, _ := appServerFixture(t, skill, tail) + source := t.TempDir() + if err := os.WriteFile(filepath.Join(source, "auth.json"), []byte(`{"token":"fixture"}`), 0600); err != nil { + t.Fatal(err) + } + t.Setenv("CODEX_HOME", source) + t.Setenv("OFFLOAD_CODEX", bin) + t.Setenv("XDG_STATE_HOME", t.TempDir()) + o := appServerOpts(t, root) + o.CodexHome = "" + o.Native.JSONSchema = "" + o.MaxWorkers = 1 + transcript := &imageRecordingCapture{} + o.Transcript = transcript + var observed []string + o.OnLine = func(line []byte) error { + observed = append(observed, string(line)) + return nil + } + record, err := Run(context.Background(), o) + if err != nil || record.Status != "ok" || record.Session != "thread-native" { + t.Fatalf("record=%+v err=%v observed=%q transcript=%q", record, err, observed, transcript.lines) + } + recordJSON, err := json.Marshal(record) + if err != nil { + t.Fatal(err) + } + encodedSecret := base64.StdEncoding.EncodeToString(secret) + for name, output := range map[string]string{ + "history record": string(recordJSON), + "observer": strings.Join(observed, "\n"), + "transcript": strings.Join(transcript.lines, "\n"), + } { + if strings.Contains(output, encodedSecret) || strings.Contains(output, string(secret)) { + t.Fatalf("%s leaked image payload: %s", name, output) + } + if !strings.Contains(output, "sha256=") || !strings.Contains(output, "bytes=") { + t.Fatalf("%s lost redaction evidence: %s", name, output) + } + } +} diff --git a/internal/worker/codex_host_test.go b/internal/worker/codex_host_test.go index 6c157a8..3acebd8 100644 --- a/internal/worker/codex_host_test.go +++ b/internal/worker/codex_host_test.go @@ -57,9 +57,6 @@ func TestCodexAppServerControlsRemainExplicit(t *testing.T) { for _, mutate := range []func(*NativeControls){ func(v *NativeControls) { v.CallerContext = false }, func(v *NativeControls) { v.PermissionMode = "default" }, - func(v *NativeControls) { - v.Images = []NativeImage{{Name: "x", MediaType: "image/png", Data: []byte("x")}} - }, func(v *NativeControls) { v.ForkFromSessionID = "fork" }, func(v *NativeControls) { v.AllowedTools = []string{"Read"} }, } { @@ -69,6 +66,17 @@ func TestCodexAppServerControlsRemainExplicit(t *testing.T) { t.Fatal("unsupported app-server control accepted") } } + withImage := *n + withImage.Images = []NativeImage{{Name: "x", MediaType: "image/png", Data: []byte("x")}} + if err := withImage.Validate("codex", "", false); err != nil { + t.Fatalf("app-server image rejected: %v", err) + } + legacy := withImage + legacy.CodexAppServer = false + legacy.SkillRoots, legacy.JSONSchema = nil, "" + if err := legacy.Validate("codex", "", false); err == nil || !strings.Contains(err.Error(), "app-server") { + t.Fatalf("legacy Codex image accepted: %v", err) + } } func TestCodexAppServerLaunchDisablesAmbientSkillSources(t *testing.T) { diff --git a/internal/worker/image_redaction.go b/internal/worker/image_redaction.go new file mode 100644 index 0000000..455b22a --- /dev/null +++ b/internal/worker/image_redaction.go @@ -0,0 +1,152 @@ +package worker + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "fmt" + "strings" +) + +const ( + imageDataPrefix = "data:image/" + malformedImageFrame = "[malformed_image_frame omitted]" +) + +var imageDataMIMEs = []string{"image/png", "image/jpeg", "image/gif", "image/webp"} + +// sanitizeCodexAppServerLine removes inline image bytes from app-server frames +// before they reach diagnostics, captures or observers. The parser consumes the +// same sanitized frame; none of its control decisions depend on image payloads. +func sanitizeCodexAppServerLine(line []byte) []byte { + if !json.Valid(line) { + return []byte(malformedImageFrame) + } + var value any + decoder := json.NewDecoder(bytes.NewReader(line)) + decoder.UseNumber() + if decoder.Decode(&value) != nil { + return []byte(malformedImageFrame) + } + changed, safe := sanitizeImageValue(&value) + if !safe { + return []byte(malformedImageFrame) + } + if !changed { + return bytes.Clone(line) + } + encoded, err := json.Marshal(value) + if err != nil { + return []byte(malformedImageFrame) + } + return encoded +} + +func sanitizeImageValue(value *any) (changed, safe bool) { + switch item := (*value).(type) { + case []any: + for i := range item { + childChanged, childSafe := sanitizeImageValue(&item[i]) + if !childSafe { + return false, false + } + changed = changed || childChanged + } + return changed, true + case map[string]any: + for key, child := range item { + childChanged, childSafe := sanitizeImageValue(&child) + if !childSafe { + return false, false + } + if childChanged { + item[key] = child + changed = true + } + } + return changed, true + case string: + if !strings.Contains(item, imageDataPrefix) && !strings.Contains(item, `\u`) && !strings.Contains(item, `\/`) { + return false, true + } + if json.Valid([]byte(item)) { + var nested any + decoder := json.NewDecoder(strings.NewReader(item)) + decoder.UseNumber() + if decoder.Decode(&nested) == nil { + nestedChanged, nestedSafe := sanitizeImageValue(&nested) + if nestedSafe && nestedChanged { + encoded, err := json.Marshal(nested) + if err == nil { + *value = string(encoded) + return true, true + } + } + } + } + replacement, changed := sanitizeEmbeddedImageDataURLs(item) + if changed { + *value = replacement + } + return changed, true + default: + return false, true + } +} + +func sanitizeEmbeddedImageDataURLs(value string) (string, bool) { + var safe strings.Builder + rest := value + changed := false + for { + start := strings.Index(rest, imageDataPrefix) + if start < 0 { + safe.WriteString(rest) + return safe.String(), changed + } + safe.WriteString(rest[:start]) + end, replacement := sanitizeImageDataURLSpan(rest[start:]) + safe.WriteString(replacement) + rest = rest[start+end:] + changed = true + } +} + +func sanitizeImageDataURLSpan(value string) (int, string) { + for _, mediaType := range imageDataMIMEs { + prefix := "data:" + mediaType + ";base64," + if !strings.HasPrefix(value, prefix) { + continue + } + end := len(prefix) + for end < len(value) && isBase64Byte(value[end]) { + end++ + } + payload := value[len(prefix):end] + data, err := base64.StdEncoding.DecodeString(payload) + if err != nil || len(data) == 0 { + return end, "[image-data-omitted]" + } + digest := sha256.Sum256(data) + return end, fmt.Sprintf("%s[omitted;sha256=%s;bytes=%d]", prefix, hex.EncodeToString(digest[:]), len(data)) + } + end := 0 + for end < len(value) && value[end] != ' ' && value[end] != '\t' && value[end] != '\r' && value[end] != '\n' { + end++ + } + return end, "[image-data-omitted]" +} + +func isBase64Byte(b byte) bool { + return b >= 'A' && b <= 'Z' || b >= 'a' && b <= 'z' || b >= '0' && b <= '9' || b == '+' || b == '/' || b == '=' +} + +func imageOmissionFrame(reason string, originalBytes int) []byte { + encoded, _ := json.Marshal(map[string]any{ + "method": "offload/image-data-omitted", + "params": map[string]any{"reason": reason, "originalBytes": originalBytes}, + }) + return encoded +} diff --git a/internal/worker/image_redaction_test.go b/internal/worker/image_redaction_test.go new file mode 100644 index 0000000..35a3827 --- /dev/null +++ b/internal/worker/image_redaction_test.go @@ -0,0 +1,219 @@ +package worker + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "io" + "strings" + "testing" +) + +type discardWriteCloser struct{ io.Writer } + +func (discardWriteCloser) Close() error { return nil } + +func TestCodexAppServerImageLinesAreSanitizedEverywhere(t *testing.T) { + secret := bytes.Repeat([]byte("private-image-byte-"), 1<<15) + encoded := base64.StdEncoding.EncodeToString(secret) + dataURL := "data:image/png;base64," + encoded + nested, _ := json.Marshal(map[string]any{"type": "image", "url": dataURL}) + frames := [][]byte{ + mustTestJSON(t, map[string]any{ + "method": "item/started", + "params": map[string]any{ + "threadId": "thread", "turnId": "turn", + "item": map[string]any{"id": "user", "type": "userMessage", "content": []any{map[string]any{"type": "image", "url": dataURL}}}, + }, + }), + mustTestJSON(t, map[string]any{ + "method": "item/completed", + "params": map[string]any{ + "threadId": "thread", "turnId": "turn", + "item": map[string]any{"id": "user", "type": "userMessage", "content": []any{map[string]any{"type": "text", "text": string(nested)}}}, + }, + }), + } + parser := newAppServerParser(discardWriteCloser{io.Discard}, Opts{Native: &NativeControls{}}) + w := newActivityWriter(parser) + w.callbackTail = true + tap := &recordingTap{} + w.tap = tap + var observed []string + w.onLine = func(line []byte) error { observed = append(observed, string(line)); return nil } + stream := append(append(append([]byte{}, frames[0]...), '\n'), frames[1]...) + for offset := 0; offset < len(stream); offset += 137 { + w.Write(stream[offset:min(offset+137, len(stream))]) + } + if err := w.finish(); err != nil { + t.Fatal(err) + } + digest := sha256.Sum256(secret) + for name, output := range map[string]string{ + "observer": strings.Join(observed, "\n"), + "capture": strings.Join(tap.lines, "\n"), + "raw": w.String(), + } { + if strings.Contains(output, encoded) || strings.Contains(output, string(secret)) { + t.Fatalf("%s leaked image data", name) + } + if !strings.Contains(output, hex.EncodeToString(digest[:])) || !strings.Contains(output, `bytes=`) { + t.Fatalf("%s lost omission evidence: %s", name, output) + } + } + if got := w.summary().Events; got != 2 { + t.Fatalf("sanitized frames changed parser summary: events=%d", got) + } +} + +func TestCodexAppServerImageSanitizerFailsClosedAndKeepsTextExact(t *testing.T) { + parser := newAppServerParser(discardWriteCloser{io.Discard}, Opts{Native: &NativeControls{}}) + w := newActivityWriter(parser) + w.callbackTail = true + tap := &recordingTap{} + w.tap = tap + var observed []string + w.onLine = func(line []byte) error { observed = append(observed, string(line)); return nil } + plain := []byte(`{"method":"notice","params":{"text":"ordinary text"}}`) + w.Write(append(append([]byte{}, plain...), '\n')) + secret := base64.StdEncoding.EncodeToString([]byte("escaped-malformed-private-image")) + malformed := []byte(`{"method":"item/completed","params":{"url":"\u0064ata:image\/png\u003bbase64\u002c` + secret) + w.Write(malformed) + if err := w.finish(); err != nil { + t.Fatal(err) + } + if len(observed) != 2 || observed[0] != string(plain) || tap.lines[0] != string(plain) { + t.Fatalf("normal text changed: observer=%q capture=%q", observed, tap.lines) + } + for _, output := range append(append([]string{}, observed...), tap.lines...) { + if strings.Contains(output, secret) || strings.Contains(output, "data:image") { + t.Fatalf("malformed image frame leaked: %s", output) + } + } + if !strings.Contains(w.String(), "malformed_image_frame") || strings.Contains(w.String(), secret) { + t.Fatalf("diagnostic did not fail closed: %s", w.String()) + } + if parser.err == nil || parser.err.Error() != "Codex app-server emitted a malformed JSON-RPC frame" { + t.Fatalf("malformed frame did not fail parser eagerly: %v", parser.err) + } + if got := string(sanitizeCodexAppServerLine([]byte("not json"))); got != malformedImageFrame { + t.Fatalf("marker-free malformed JSON was not omitted: %q", got) + } +} + +func TestCodexAppServerImageSanitizerHandlesJSONEscapedSlash(t *testing.T) { + secret := []byte("escaped-slash-private-image") + encoded := base64.StdEncoding.EncodeToString(secret) + line := []byte(`{"method":"item/started","params":{"url":"\u0064ata:image\/png;base64,` + encoded + `"}}`) + sanitized := sanitizeCodexAppServerLine(line) + if bytes.Contains(sanitized, []byte(encoded)) || !bytes.Contains(sanitized, []byte("sha256=")) || !json.Valid(sanitized) { + t.Fatalf("escaped image URL was not safely redacted: %s", sanitized) + } +} + +func TestCodexAppServerNestedEscapedImageURLIsSanitized(t *testing.T) { + secret := base64.StdEncoding.EncodeToString([]byte("nested-escaped-private-image")) + nested := `{"url":"\u0064ata:image\/png\u003bbase64\u002c` + secret + `"}` + line := mustTestJSON(t, map[string]any{ + "method": "item/completed", "params": map[string]any{"id": "kept", "text": nested}, + }) + sanitized := sanitizeCodexAppServerLine(line) + if bytes.Contains(sanitized, []byte(secret)) || !bytes.Contains(sanitized, []byte("sha256=")) || !bytes.Contains(sanitized, []byte(`"id":"kept"`)) || !json.Valid(sanitized) { + t.Fatalf("nested escaped image URL leaked or lost protocol evidence: %s", sanitized) + } +} + +func TestCodexAppServerEmbeddedImageURLPreservesTerminalReport(t *testing.T) { + secret := []byte("embedded-private-image") + encoded := base64.StdEncoding.EncodeToString(secret) + report := "before data:image/jpeg;base64," + encoded + " after" + frame := mustTestJSON(t, map[string]any{ + "method": "turn/completed", + "params": map[string]any{ + "threadId": "thread", "turn": map[string]any{ + "id": "turn", "status": "completed", "error": nil, + "items": []any{map[string]any{"type": "agentMessage", "text": report}}, + }, + }, + }) + parser := newAppServerParser(discardWriteCloser{io.Discard}, Opts{Native: &NativeControls{}}) + parser.threadID, parser.turnID, parser.s.Session = "thread", "turn", "thread" + sanitized := sanitizeCodexAppServerLine(frame) + parser.feed(sanitized) + summary := parser.summary() + if parser.err != nil || summary.Session != "thread" || summary.Result == nil || summary.Result.IsError { + t.Fatalf("terminal control fields changed: summary=%+v err=%v", summary, parser.err) + } + got := summary.Result.Result + if !strings.HasPrefix(got, "before ") || !strings.HasSuffix(got, " after") || !strings.Contains(got, "sha256=") || !strings.Contains(got, "bytes=22") || strings.Contains(got, encoded) { + t.Fatalf("embedded image was not span-redacted: %q", got) + } +} + +func TestCodexAppServerMalformedAndUnsupportedEmbeddedImagesKeepFrame(t *testing.T) { + for _, value := range []string{ + "before data:image/png;base64,PRIVATE after", + "before data:image/svg+xml;base64,U0VDUkVU after", + } { + line := mustTestJSON(t, map[string]any{"method": "notice", "params": map[string]any{"text": value, "control": "kept"}}) + sanitized := sanitizeCodexAppServerLine(line) + var frame struct { + Method string `json:"method"` + Params struct { + Text, Control string + } `json:"params"` + } + if err := json.Unmarshal(sanitized, &frame); err != nil || frame.Method != "notice" || frame.Params.Control != "kept" || !strings.HasPrefix(frame.Params.Text, "before ") || !strings.HasSuffix(frame.Params.Text, " after") || !strings.Contains(frame.Params.Text, "[image-data-omitted]") { + t.Fatalf("embedded malformed URL dropped frame: %s err=%v", sanitized, err) + } + } +} + +func TestCodexAppServerLargeAndOversizedImageLinesUseSafeBoundedOutput(t *testing.T) { + secret := bytes.Repeat([]byte("large-private-image"), 1<<16) + line := mustTestJSON(t, map[string]any{ + "method": "item/started", + "params": map[string]any{ + "item": map[string]any{"type": "userMessage", "content": []any{map[string]any{"type": "image", "url": "data:image/webp;base64," + base64.StdEncoding.EncodeToString(secret)}}}, + }, + }) + parser := newAppServerParser(discardWriteCloser{io.Discard}, Opts{Native: &NativeControls{}}) + w := newActivityWriter(parser) + tap := &recordingTap{} + w.tap = tap + var observed []string + w.onLine = func(line []byte) error { observed = append(observed, string(line)); return nil } + for offset := 0; offset < len(line); offset += 4093 { + w.Write(line[offset:min(offset+4093, len(line))]) + } + w.Write([]byte("\n")) + if len(observed) != 1 || len(observed[0]) >= maxCallbackLine || strings.Contains(observed[0], base64.StdEncoding.EncodeToString(secret)) || len(w.raw) >= maxRawKept { + t.Fatalf("large image line was not reduced before retention: observed=%d raw=%d", len(observed), len(w.raw)) + } + + oversized := newActivityWriter(newAppServerParser(discardWriteCloser{io.Discard}, Opts{Native: &NativeControls{}})) + oversized.lineLimit = 64 + oversized.callbackTail = true + overTap := &recordingTap{} + oversized.tap = overTap + var overObserved []string + oversized.onLine = func(line []byte) error { overObserved = append(overObserved, string(line)); return nil } + oversized.Write(line) + if err := oversized.finish(); err != nil { + t.Fatal(err) + } + if len(overObserved) != 1 || !strings.Contains(overObserved[0], "line_too_large") || strings.Contains(oversized.String(), "data:image") || len(overTap.skipped) != 1 { + t.Fatalf("oversized line did not become safe omission: observer=%q raw=%q skipped=%q", overObserved, oversized.String(), overTap.skipped) + } +} + +func mustTestJSON(t *testing.T, value any) []byte { + t.Helper() + encoded, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + return encoded +} diff --git a/internal/worker/native_controls.go b/internal/worker/native_controls.go index 9e52682..3e9b189 100644 --- a/internal/worker/native_controls.go +++ b/internal/worker/native_controls.go @@ -49,8 +49,11 @@ func (n *NativeControls) Validate(backend, resume string, toolsDisabled bool) er if toolsDisabled || n.Extraction || n.RestrictedReadOnly || len(n.AllowedTools) > 0 { return errors.New("Codex host controls cannot enforce tool-free execution or native tool allowlists") } - if n.SkillDirectory != "" || len(n.Images) > 0 || n.ForkFromSessionID != "" { - return errors.New("Codex host controls do not yet support plugin Skills, images or forks") + if n.SkillDirectory != "" || n.ForkFromSessionID != "" { + return errors.New("Codex host controls do not yet support plugin Skills or forks") + } + if len(n.Images) > 0 && !n.CodexAppServer { + return errors.New("Codex image input requires the app-server protocol") } if n.PermissionMode != "bypassPermissions" { return errors.New("Codex host controls require explicit owner bypassPermissions") diff --git a/internal/worker/output.go b/internal/worker/output.go index 86b3e08..a09d0c5 100644 --- a/internal/worker/output.go +++ b/internal/worker/output.go @@ -56,12 +56,13 @@ type activityWriter struct { mu sync.Mutex lineMu sync.Mutex // keeps onLine calls in stream order without holding mu during the callback parser eventParser - onLine func([]byte) error // optional; sees each complete line of at most maxCallbackLine bytes - tap lineTap // optional; sees every complete line kept, and notes of what was not kept - lines [][]byte // lines completed by the current Write, delivered after mu is released - pending []byte // bytes of the current, unfinished line - skipping bool // inside a line longer than maxLineKept; discard up to its newline - skippedN int // bytes of that line seen so far + lineFilter func([]byte) []byte // optional; sanitizes complete lines before every retained or external use + onLine func([]byte) error // optional; sees each complete line of at most maxCallbackLine bytes + tap lineTap // optional; sees every complete line kept, and notes of what was not kept + lines [][]byte // lines completed by the current Write, delivered after mu is released + pending []byte // bytes of the current, unfinished line + skipping bool // inside a line longer than maxLineKept; discard up to its newline + skippedN int // bytes of that line seen so far raw []byte rawCapped bool last atomic.Int64 // 相对 activityEpoch 的单调时钟纳秒数 @@ -69,6 +70,9 @@ type activityWriter struct { func newActivityWriter(p eventParser) *activityWriter { w := &activityWriter{parser: p, callbackLimit: maxCallbackLine, lineLimit: maxLineKept} + if _, ok := p.(*appServerParser); ok { + w.lineFilter = sanitizeCodexAppServerLine + } w.last.Store(time.Since(activityEpoch).Nanoseconds()) return w } @@ -95,11 +99,13 @@ func (w *activityWriter) Write(p []byte) (int, error) { } func (w *activityWriter) write(p []byte) { - if room := maxRawKept - len(w.raw); room > 0 { - w.raw = append(w.raw, p[:min(room, len(p))]...) - } - if len(w.raw) >= maxRawKept { - w.rawCapped = true + if w.lineFilter == nil { + if room := maxRawKept - len(w.raw); room > 0 { + w.raw = append(w.raw, p[:min(room, len(p))]...) + } + if len(w.raw) >= maxRawKept { + w.rawCapped = true + } } for data := p; len(data) > 0; { i := bytes.IndexByte(data, '\n') @@ -134,28 +140,20 @@ func (w *activityWriter) addPending(b []byte) { } func (w *activityWriter) endLine(emit bool) { - if w.skipping && w.tap != nil { - w.tap.Skipped("line_too_large", w.skippedN) + if w.skipping { + if w.tap != nil { + w.tap.Skipped("line_too_large", w.skippedN) + } + if w.lineFilter != nil { + w.deliverLine(imageOmissionFrame("line_too_large", w.skippedN), emit) + } } if !w.skipping { if line := bytes.TrimSpace(w.pending); len(line) > 0 { - if w.parser != nil { - w.parser.feed(line) - } - if w.tap != nil { - if emit || json.Valid(line) { - w.tap.Line(line) - } else { - w.tap.Skipped("unterminated_final_line", len(line)) - } - } - limit := w.callbackLimit - if limit == 0 { - limit = maxCallbackLine - } - if emit && w.onLine != nil && len(line) <= limit { - w.lines = append(w.lines, bytes.Clone(line)) + if w.lineFilter != nil { + line = w.lineFilter(line) } + w.deliverLine(line, emit) } } w.skipping, w.skippedN = false, 0 @@ -166,12 +164,55 @@ func (w *activityWriter) endLine(emit bool) { } } +func (w *activityWriter) deliverLine(line []byte, emit bool) { + if w.lineFilter != nil { + w.appendRawLine(line, emit) + } + if w.parser != nil { + w.parser.feed(line) + } + if w.tap != nil { + if emit || json.Valid(line) { + w.tap.Line(line) + } else { + w.tap.Skipped("unterminated_final_line", len(line)) + } + } + limit := w.callbackLimit + if limit == 0 { + limit = maxCallbackLine + } + if emit && w.onLine != nil && len(line) <= limit { + w.lines = append(w.lines, bytes.Clone(line)) + } +} + +func (w *activityWriter) appendRawLine(line []byte, newline bool) { + wanted := len(line) + if newline { + wanted++ + } + room := maxRawKept - len(w.raw) + if wanted > room { + w.rawCapped = true + } + if room > 0 { + kept := min(room, len(line)) + w.raw = append(w.raw, line[:kept]...) + room -= kept + if kept == len(line) && newline && room > 0 { + w.raw = append(w.raw, '\n') + room-- + } + } +} + // finish parses a final line that had no trailing newline. Call it once the worker has exited. func (w *activityWriter) finish() error { w.lineMu.Lock() defer w.lineMu.Unlock() w.mu.Lock() - if len(w.pending) > 0 { + if len(w.pending) > 0 || w.lineFilter != nil && w.skipping { w.endLine(w.callbackTail) } lines := w.lines