redact: a ping between two pieces of a placeholder no longer leaves it in the agent's arguments (#5287)
The Writer holds an event whose text ends in part of a placeholder and
joins it with the next piece. A keepalive event in between (Anthropic's
ping, Responses' response.in_progress or response.queued) made it write
the held piece as it was. The rest of the placeholder came in the next
piece, and neither piece could be restored. A slow model writing a masked
value through Claude Code's Write/Edit put {{SECRET_…}} or a stray { on
disk. magpie-community/plugins#738 committed two German texts as
{{SECRET_5dz6uy27}} and {{SECRET_2zh6t2jw}}.
Keepalive events now go out ahead of the held piece, which stays held for
its continuation. This covers every route that restores through
redact.Writer (Anthropic, Responses, Codex backend, plugins). Chat's
keepalive is a comment, which was already passed through (#2402), and
Gemini has none.
Run on mote at fe6533ad8 (= origin/main when pushed):
- go test ./internal/redact ./internal/masking: ok.
- go test ./internal/gateway -run 'Keepalive|Masked|Mask|Redact|Ping|Quiet|Restore|Placeholder': ok.
- GOOS=linux and GOOS=windows go vet of internal/redact and internal/gateway: ok.
- gofmt -l: clean.
Broken by hand: with writer.go back at main, both new tests are red.
- TestWriterHeldAcrossKeepalive: "anthropic ping cut at 49", a stray {.
- TestMaskedToolArgsSplitAroundPing: the agent's partial_json is
{"content":"mail {{EMAIL_asf2pa5q}}"}.
Not tried:
- The false positive itself. None of the regex rules mask plausible German
texts for these strings (Mask and MaskJSON with Secrets+Personal), so it
was most likely the local model. That wasn't run, and the PR's German is
unknown.
- A real Anthropic or Codex session.
- Placeholders the vendor sends back after a magpie restart. Values are
kept in memory only, and that is unchanged.
- The full suite runs after the push.
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A model that pauses in the middle of a placeholder while it writes a
|
||||
// tool call's arguments: magpie keeps an Anthropic client alive with a
|
||||
// ping, and the agent's arguments still have the value, not the
|
||||
// placeholder. The ping released the held first piece with the start of
|
||||
// the placeholder in it, the next piece came with the rest, and Claude
|
||||
// Code wrote {{…}} into the file (magpie-community/plugins#738).
|
||||
func TestMaskedToolArgsSplitAroundPing(t *testing.T) {
|
||||
fresh(t)
|
||||
quietFast(t)
|
||||
pe := pingEvery
|
||||
pingEvery = 10 * time.Millisecond
|
||||
t.Cleanup(func() { pingEvery = pe })
|
||||
const email = "moon.shard@proton.me"
|
||||
heard := make(chan struct{})
|
||||
var timedOut atomic.Bool
|
||||
var sent []byte
|
||||
chunk := func(args string, finish any) string {
|
||||
b, _ := json.Marshal(map[string]any{"id": "c1", "model": "m1", "choices": []any{map[string]any{
|
||||
"index": 0, "finish_reason": finish,
|
||||
"delta": map[string]any{"tool_calls": []any{map[string]any{"index": 0, "id": "call_1", "type": "function",
|
||||
"function": map[string]any{"name": "Write", "arguments": args}}}}}}})
|
||||
return "data: " + string(b) + "\n\n"
|
||||
}
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sent, _ = io.ReadAll(r.Body)
|
||||
p := regexp.MustCompile(`\{\{EMAIL_[a-z2-7]{8}\}\}`).FindString(string(sent))
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
if p == "" {
|
||||
io.WriteString(w, chunk(`{}`, "tool_calls")+"data: [DONE]\n\n")
|
||||
return
|
||||
}
|
||||
args := `{"content":"mail ` + p + `"}`
|
||||
cut := strings.Index(args, p) + 9 // {{EMAIL_x
|
||||
io.WriteString(w, chunk(args[:cut], nil))
|
||||
w.(http.Flusher).Flush()
|
||||
select {
|
||||
case <-heard:
|
||||
case <-time.After(3 * time.Second):
|
||||
timedOut.Store(true)
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
io.WriteString(w, chunk(args[cut:], nil)+chunk("", "tool_calls")+"data: [DONE]\n\n")
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "fixture", Name: "Fixture", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gw := httptest.NewServer(New().Handler())
|
||||
t.Cleanup(gw.Close)
|
||||
body := `{"model":"fixture/m1","stream":true,"max_tokens":256,
|
||||
"tools":[{"name":"Write","description":"write a file","input_schema":{"type":"object","properties":{"content":{"type":"string"}}}}],
|
||||
"messages":[{"role":"user","content":"write my address ` + email + ` into notes.md"}]}`
|
||||
resp, err := http.Post(gw.URL+"/v1/messages", "application/json", strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var once sync.Once
|
||||
var all strings.Builder
|
||||
rd := bufio.NewReader(resp.Body)
|
||||
for {
|
||||
line, err := rd.ReadString('\n')
|
||||
all.WriteString(line)
|
||||
if strings.HasPrefix(line, "event: ping") && strings.Contains(all.String(), `"tool_use"`) {
|
||||
once.Do(func() { close(heard) })
|
||||
}
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(sent), email) {
|
||||
t.Fatalf("the address went to the vendor: %s", sent)
|
||||
}
|
||||
out := all.String()
|
||||
if timedOut.Load() || !strings.Contains(out, "event: ping") {
|
||||
t.Fatalf("no ping between the pieces (timed out %v):\n%s", timedOut.Load(), out)
|
||||
}
|
||||
var js strings.Builder
|
||||
for _, ev := range strings.Split(out, "\n\n") {
|
||||
_, d, ok := strings.Cut(ev, "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var e struct {
|
||||
Delta struct {
|
||||
PartialJSON string `json:"partial_json"`
|
||||
}
|
||||
}
|
||||
json.Unmarshal([]byte(d), &e)
|
||||
js.WriteString(e.Delta.PartialJSON)
|
||||
}
|
||||
var in map[string]string
|
||||
if err := json.Unmarshal([]byte(js.String()), &in); err != nil || in["content"] != "mail "+email {
|
||||
t.Fatalf("the agent's arguments %q (%v):\n%s", js.String(), err, out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package redact
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A placeholder split between two pieces of a tool call's arguments comes
|
||||
// back whole when a keepalive event comes between the pieces: Anthropic's
|
||||
// ping, which the API and magpie's own encoder send while the model is
|
||||
// slow, and Responses' response.in_progress, magpie's keepalive on that
|
||||
// protocol. The ping released the first piece as it was, and the agent
|
||||
// wrote {{SECRET_…}} into a file where the model had written German
|
||||
// (magpie-community/plugins#738, sensenova's prune_old_keys texts).
|
||||
func TestWriterHeldAcrossKeepalive(t *testing.T) {
|
||||
const v = `Alte magpie-*-Keys dieses Kontos werden gelöscht; manuelle Keys und Keys anderer Konten bleiben „erhalten".`
|
||||
p := placeholder("SECRET", v)
|
||||
anthropic := func(s string) string {
|
||||
b, _ := json.Marshal(map[string]any{"type": "content_block_delta", "index": 1, "delta": map[string]any{"type": "input_json_delta", "partial_json": s}})
|
||||
return "event: content_block_delta\ndata: " + string(b) + "\n\n"
|
||||
}
|
||||
responses := func(typ string) func(s string) string {
|
||||
return func(s string) string {
|
||||
b, _ := json.Marshal(map[string]any{"type": typ, "item_id": "fc_1", "output_index": 1, "delta": s})
|
||||
return "event: " + typ + "\ndata: " + string(b) + "\n\n"
|
||||
}
|
||||
}
|
||||
const (
|
||||
ping = "event: ping\ndata: {\"type\": \"ping\"}\n\n"
|
||||
inProgress = `event: response.in_progress` + "\n" + `data: {"type":"response.in_progress","sequence_number":7,"response":{"id":"resp_1","object":"response","status":"in_progress","model":"gpt-5.5","output":[]}}` + "\n\n"
|
||||
)
|
||||
// what the agent puts together from the events' pieces
|
||||
partial := func(d string) string {
|
||||
var x struct {
|
||||
Delta json.RawMessage
|
||||
}
|
||||
json.Unmarshal([]byte(d), &x)
|
||||
var s string
|
||||
if json.Unmarshal(x.Delta, &s) == nil {
|
||||
return s
|
||||
}
|
||||
var o struct {
|
||||
PartialJSON string `json:"partial_json"`
|
||||
}
|
||||
json.Unmarshal(x.Delta, &o)
|
||||
return o.PartialJSON
|
||||
}
|
||||
args := `{"file_path":"/x/index.mjs","new_string":"de: \"` + p + `\","}`
|
||||
patch := "*** Update File: index.mjs\n+ de: \"" + p + "\",\n"
|
||||
for _, c := range []struct {
|
||||
name, keep, text string
|
||||
ev func(string) string
|
||||
json bool
|
||||
}{
|
||||
{"anthropic ping", ping, args, anthropic, true},
|
||||
{"responses in_progress", inProgress, args, responses("response.function_call_arguments.delta"), true},
|
||||
{"responses custom tool in_progress", inProgress, patch, responses("response.custom_tool_call_input.delta"), false},
|
||||
} {
|
||||
at := strings.Index(c.text, p)
|
||||
for cut := at + 1; cut < at+len(p); cut++ {
|
||||
rec := httptest.NewRecorder()
|
||||
rec.Header().Set("Content-Type", "text/event-stream")
|
||||
w := NewWriter(rec)
|
||||
w.WriteHeader(200)
|
||||
for _, e := range []string{c.ev(c.text[:cut]), c.keep, c.ev(c.text[cut:])} {
|
||||
w.Write([]byte(e))
|
||||
}
|
||||
w.Finish()
|
||||
var got strings.Builder
|
||||
n := 0
|
||||
for _, e := range strings.Split(rec.Body.String(), "\n\n") {
|
||||
_, d, ok := strings.Cut(e, "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if !strings.Contains(d, `"delta"`) {
|
||||
continue
|
||||
}
|
||||
got.WriteString(partial(d))
|
||||
}
|
||||
if n != 3 {
|
||||
t.Fatalf("%s at %d: %d events, want 3:\n%s", c.name, cut, n, rec.Body.String())
|
||||
}
|
||||
if c.json {
|
||||
var in map[string]string
|
||||
if err := json.Unmarshal([]byte(got.String()), &in); err != nil || in["new_string"] != `de: "`+v+`",` {
|
||||
t.Fatalf("%s cut at %d: args %q: %v", c.name, cut, got.String(), err)
|
||||
}
|
||||
} else if want := strings.Replace(c.text, p, v, 1); got.String() != want {
|
||||
t.Fatalf("%s cut at %d:\n got %q\nwant %q", c.name, cut, got.String(), want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -223,6 +223,14 @@ func (rw *Writer) event(ev []byte) error {
|
||||
_, err := rw.w.Write([]byte(restore(string(ev), false, rw.count())))
|
||||
return err
|
||||
}
|
||||
if rw.pending != nil && waiting(name, data) {
|
||||
// a keepalive between two pieces of a text goes on ahead of the
|
||||
// piece held: released for it, the held piece went out with the
|
||||
// start of its placeholder as it was, the next piece with the
|
||||
// rest, and neither was a placeholder to put back (#5287)
|
||||
_, err := rw.w.Write(rebuild(pre, restoreJSON(data, rw.count()), post))
|
||||
return err
|
||||
}
|
||||
ctx := name + "|" + eventCtx(data)
|
||||
// the starts of placeholders the last event ended in go on here
|
||||
var carry map[string]string
|
||||
@@ -280,6 +288,22 @@ func (rw *Writer) event(ev []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// waitEvents are the events a stream sends while the model is slow, which
|
||||
// say nothing of the answer: Anthropic's ping, which its API and magpie's
|
||||
// encoder send in the middle of a tool call's arguments, Responses'
|
||||
// keepalive, and response.in_progress and response.queued, magpie's
|
||||
// keepalive on that protocol.
|
||||
var waitEvents = []string{"ping", "keepalive", "response.in_progress", "response.queued"}
|
||||
|
||||
// waiting says an event of name with data is one of waitEvents.
|
||||
func waiting(name string, data []byte) bool {
|
||||
typ := typeOf(data)
|
||||
if typ == "" {
|
||||
typ = name
|
||||
}
|
||||
return slices.Contains(waitEvents, typ)
|
||||
}
|
||||
|
||||
// sealedText says a string of a vendor's answer goes on as it came: what the
|
||||
// vendor sealed (signatureKeys) and a file's encoded data.
|
||||
func sealedText(key, s string) bool {
|
||||
|
||||
Reference in New Issue
Block a user