fix: harden agent writeback safety

This commit is contained in:
Yoilun
2026-05-25 21:26:37 +08:00
parent a01dd36fb0
commit d7b75a1112
6 changed files with 341 additions and 34 deletions

View File

@@ -250,6 +250,69 @@ func TestAgentValidateEndpointReturnsBadRequestForInvalidBody(t *testing.T) {
}
}
func TestAgentValidateEndpointRejectsOversizeBody(t *testing.T) {
root := t.TempDir()
agentsDir := filepath.Join(root, "agents")
if err := os.MkdirAll(agentsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(agentsDir, "backend.toml"), []byte(`name = "旧名称"`+"\n"), 0o644); err != nil {
t.Fatal(err)
}
body := `{"content":"` + strings.Repeat("a", 1024*1024+1) + `"}`
req := httptest.NewRequest(http.MethodPost, "/api/agents/backend/validate", bytes.NewBufferString(body))
rec := httptest.NewRecorder()
New(app.Config{CodexHome: root, HTTPAddr: "127.0.0.1:0"}).ServeHTTP(rec, req)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want %d, body = %s", rec.Code, http.StatusRequestEntityTooLarge, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "请求体过大") {
t.Fatalf("expected Chinese oversize error, got %s", rec.Body.String())
}
}
func TestAgentValidateEndpointRejectsTrailingJSON(t *testing.T) {
root := t.TempDir()
agentsDir := filepath.Join(root, "agents")
if err := os.MkdirAll(agentsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(agentsDir, "backend.toml"), []byte(`name = "旧名称"`+"\n"), 0o644); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/agents/backend/validate", bytes.NewBufferString(`{"content":"name = \"新名称\"\n"} {}`))
rec := httptest.NewRecorder()
New(app.Config{CodexHome: root, HTTPAddr: "127.0.0.1:0"}).ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d, body = %s", rec.Code, http.StatusBadRequest, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "请求体不是有效 JSON") {
t.Fatalf("expected Chinese invalid JSON error, got %s", rec.Body.String())
}
}
func TestAgentWritebackErrorsAreSanitized(t *testing.T) {
root := t.TempDir()
if err := os.MkdirAll(filepath.Join(root, "agents"), 0o755); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/agents/missing/validate", bytes.NewBufferString(`{"content":"name = \"新名称\"\n"}`))
rec := httptest.NewRecorder()
New(app.Config{CodexHome: root, HTTPAddr: "127.0.0.1:0"}).ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want %d, body = %s", rec.Code, http.StatusNotFound, rec.Body.String())
}
if strings.Contains(rec.Body.String(), root) || strings.Contains(rec.Body.String(), "no such file") || !strings.Contains(rec.Body.String(), "目标智能体不存在") {
t.Fatalf("error leaked path or raw OS text: %s", rec.Body.String())
}
}
func TestAgentWriteEndpointCreatesBackupAndRejectsConflicts(t *testing.T) {
root := t.TempDir()
agentsDir := filepath.Join(root, "agents")