diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e4b446..7f7c27b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,7 @@ All notable changes to this project are documented in this file. The format is b - **Findings CSV formula cells**: `FindingsCSV` prefixes name, class, summary, task, and other text fields that start with `=`, `+`, `-`, `@`, tab, or CR so Excel/LibreOffice do not evaluate them as formulas when the export is opened. - **Asset service links**: the Services tab only uses an asset URL as `href` when it is `http:` or `https:`. `javascript:`, `data:`, and other schemes render as text. +- **Chat session directories**: `ChatAgent.Chat` accepts only `[A-Za-z0-9_-]` session ids (at most 64 bytes) before joining them under `/sessions`, so `..` and path separators cannot escape that directory. - **ask_operator image_path**: the screenshot path must resolve inside the task working directory (`/tasks/`). Absolute paths, `..` segments, and symlinks that leave that directory are refused, so the tool cannot copy an arbitrary server image into the operator transcript. - **insert_assets fail-closed**: when intercept or task allow/block rules cannot be loaded, `insert_assets` refuses the whole call instead of evaluating an empty rule set (which allowed every asset). The tool result does not include the underlying database error. - **BlobRange length no longer wraps int64**: `offset+length > size` overflowed when length was near MaxInt64, so the cap was skipped and `make([]byte, length)` could exhaust memory. The bound is now `length > size-offset`. diff --git a/agent/chat.go b/agent/chat.go index 7d20b90..65cd595 100644 --- a/agent/chat.go +++ b/agent/chat.go @@ -2,8 +2,10 @@ package agent import ( "context" + "fmt" "os" "path/filepath" + "strings" "time" "github.com/Autumn-27/artex/db" @@ -98,6 +100,33 @@ func chatSystem(agentKey, dataDir, workDir string) string { // DefaultAssistantPrompt. type chatVars struct{ DataDir, Now string } +const maxChatSessionID = 64 + +// validChatSessionID is the session-directory name contract. Production uses +// "conv-" plus a decimal id; tests use hyphenated suffixes. Path separators +// and ".." are rejected so Join cannot leave /sessions. +func validChatSessionID(id string) bool { + if id == "" || len(id) > maxChatSessionID { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + switch { + case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '_', c == '-': + default: + return false + } + } + return true +} + +func sessionDirInside(workDir, sessionWorkDir string) bool { + base := filepath.Clean(filepath.Join(workDir, "sessions")) + clean := filepath.Clean(sessionWorkDir) + sep := string(os.PathSeparator) + return clean == base || strings.HasPrefix(clean, base+sep) +} + // Chat runs ONE turn of a conversation with the agent identified by agentKey, // resuming prior history keyed by sessionID. maxTurns is the per-turn agent step // budget (0 = unlimited). maxDuration is the wall-clock run budget per turn @@ -114,9 +143,15 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin ws.Enabled = false } + if !validChatSessionID(sessionID) { + return "", fmt.Errorf("invalid session id %q", sessionID) + } // Per-session working directory: /sessions// // Isolates file writes across conversations, mirroring how workers use i/. sessionWorkDir := filepath.Join(c.workDir, "sessions", sessionID) + if !sessionDirInside(c.workDir, sessionWorkDir) { + return "", fmt.Errorf("invalid session id %q", sessionID) + } _ = os.MkdirAll(sessionWorkDir, 0o755) ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir) diff --git a/agent/chat_session_id_test.go b/agent/chat_session_id_test.go new file mode 100644 index 0000000..e6bc49e --- /dev/null +++ b/agent/chat_session_id_test.go @@ -0,0 +1,79 @@ +package agent + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestValidChatSessionID(t *testing.T) { + ok := []string{ + "conv-1", + "conv-stable", + "conv-hook-reach", + "conv-987654", + "conv-dial-probe", + "conv-redirect-probe", + "conv-new", + "conv-broken", + "conv-signed", + "conv-" + strings.Repeat("9", 19), + } + for _, id := range ok { + if !validChatSessionID(id) { + t.Fatalf("%q rejected", id) + } + } + bad := []string{ + "", + ".", + "..", + "../etc", + "conv/../etc", + `conv\windows`, + "/etc/passwd", + "conv-1/foo", + "a.b", + "conv 1", + "conv:1", + strings.Repeat("a", maxChatSessionID+1), + } + for _, id := range bad { + if validChatSessionID(id) { + t.Fatalf("%q accepted", id) + } + } +} + +func TestChatRejectsUnsafeSessionID(t *testing.T) { + p := &sessionProbe{} + workDir := t.TempDir() + c := NewChatAgent(p, "test-model", workDir, nil, 100000) + for _, id := range []string{"..", "../etc", "conv/../etc", `..\windows`, "/etc/passwd", "conv-1/foo"} { + if _, err := c.Chat(t.Context(), "assistant", id, "hello", 1, 0, false, nil); err == nil { + t.Fatalf("%q accepted", id) + } + if n := len(p.seen()); n != 0 { + t.Fatalf("provider called for %q: %d calls", id, n) + } + } + entries, err := os.ReadDir(workDir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 0 { + t.Fatalf("unsafe session id created %v under workDir", names(entries)) + } + if _, err := os.Stat(filepath.Join(workDir, "etc")); !os.IsNotExist(err) { + t.Fatalf("escaped path created: %v", err) + } +} + +func names(entries []os.DirEntry) []string { + out := make([]string, len(entries)) + for i, e := range entries { + out[i] = e.Name() + } + return out +}