|
| 1 | +package main |
| 2 | + |
| 3 | +// Regression tests for the 2026-08 security audit — serve/API quick wins. |
| 4 | + |
| 5 | +import ( |
| 6 | + "encoding/json" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "strings" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/BackendStack21/odek/internal/llm" |
| 14 | + "github.com/BackendStack21/odek/internal/session" |
| 15 | + |
| 16 | + golangws "golang.org/x/net/websocket" |
| 17 | +) |
| 18 | + |
| 19 | +// TestAudit_ExportMarkdown_FenceBreakout audits the finding that the |
| 20 | +// markdown export used a fixed 4-backtick fence: any transcript line of |
| 21 | +// exactly ```` closed it early, letting model/tool output forge document |
| 22 | +// structure in the "human-shareable" export. The fence must grow longer |
| 23 | +// than the longest backtick run in the fenced content. |
| 24 | +func TestAudit_ExportMarkdown_FenceBreakout(t *testing.T) { |
| 25 | + sess := &session.Session{ |
| 26 | + ID: "audit-fence-test", |
| 27 | + Task: "fence test", |
| 28 | + Messages: []llm.Message{ |
| 29 | + {Role: "user", Content: "check this"}, |
| 30 | + {Role: "assistant", Content: "````\n# FORGED HEADING\n```normal```\n````"}, |
| 31 | + {Role: "tool", Name: "browser", Content: "````\n## forged tool section\n````"}, |
| 32 | + }, |
| 33 | + } |
| 34 | + out := exportSessionMarkdown(sess) |
| 35 | + // The assistant content's longest run is 4 backticks → fence must be ≥5. |
| 36 | + // A 5-backtick opener cannot be closed by any 4-backtick line in the |
| 37 | + // body, so the forged structure stays inside the code block. |
| 38 | + if !strings.Contains(out, "`````markdown") { |
| 39 | + t.Errorf("expected a 5-backtick fence around assistant content:\n%s", out) |
| 40 | + } |
| 41 | + if !strings.Contains(out, "`````text") { |
| 42 | + t.Errorf("expected a 5-backtick fence around tool content:\n%s", out) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +// TestAudit_CodeFence pins the fence-length computation directly. |
| 47 | +func TestAudit_CodeFence(t *testing.T) { |
| 48 | + cases := []struct { |
| 49 | + body string |
| 50 | + want int |
| 51 | + }{ |
| 52 | + {"plain text", 4}, |
| 53 | + {"has `one` backtick", 4}, |
| 54 | + {"has ```three```", 4}, |
| 55 | + {"has ````four````", 5}, |
| 56 | + {"has ```````seven```````", 8}, |
| 57 | + } |
| 58 | + for _, c := range cases { |
| 59 | + if got := len(codeFence(c.body)); got != c.want { |
| 60 | + t.Errorf("codeFence(%q) length = %d, want %d", c.body, got, c.want) |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +// TestAudit_ServeHTTPServerTimeouts pins the slowloris hardening: without |
| 66 | +// ReadHeaderTimeout/IdleTimeout, any unauthenticated client could hold |
| 67 | +// half-open connections forever (rate limiting and the CSRF token only |
| 68 | +// apply after the request line arrives). |
| 69 | +func TestAudit_ServeHTTPServerTimeouts(t *testing.T) { |
| 70 | + srv := newServeHTTPServer(http.NewServeMux()) |
| 71 | + if srv.ReadHeaderTimeout <= 0 { |
| 72 | + t.Errorf("ReadHeaderTimeout = %v, want > 0", srv.ReadHeaderTimeout) |
| 73 | + } |
| 74 | + if srv.IdleTimeout <= 0 { |
| 75 | + t.Errorf("IdleTimeout = %v, want > 0", srv.IdleTimeout) |
| 76 | + } |
| 77 | +} |
| 78 | + |
| 79 | +// TestAudit_IDGenerators pins the conn/run ID generators: correct prefix, |
| 80 | +// fixed length, and uniqueness. (The 2026-08 fix made them fail closed on |
| 81 | +// crypto/rand errors; the happy path must keep producing distinct IDs.) |
| 82 | +func TestAudit_IDGenerators(t *testing.T) { |
| 83 | + seenConn := map[string]bool{} |
| 84 | + for i := 0; i < 100; i++ { |
| 85 | + id := newWSConnID() |
| 86 | + if !strings.HasPrefix(id, "conn-") || len(id) != len("conn-")+16 { |
| 87 | + t.Fatalf("newWSConnID() = %q, want conn- + 16 hex chars", id) |
| 88 | + } |
| 89 | + if seenConn[id] { |
| 90 | + t.Fatalf("newWSConnID() repeated: %s", id) |
| 91 | + } |
| 92 | + seenConn[id] = true |
| 93 | + } |
| 94 | + seenRun := map[string]bool{} |
| 95 | + for i := 0; i < 100; i++ { |
| 96 | + id := newRunID() |
| 97 | + if !strings.HasPrefix(id, "run-") || len(id) != len("run-")+20 { |
| 98 | + t.Fatalf("newRunID() = %q, want run- + 20 hex chars", id) |
| 99 | + } |
| 100 | + if seenRun[id] { |
| 101 | + t.Fatalf("newRunID() repeated: %s", id) |
| 102 | + } |
| 103 | + seenRun[id] = true |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +// TestAudit_WebSocketInvalidModelRejectedEarly pins the WS-loop ordering |
| 108 | +// fix: an invalid model ID must be rejected before the switch is applied to |
| 109 | +// the agent (a rejected ID used to stay active and silently reused by the |
| 110 | +// next prompt sent without a model field). Runs the production handleWS |
| 111 | +// loop with the mock-LLM harness so agent construction succeeds without a |
| 112 | +// real API key; the invalid model is rejected before any LLM call, so the |
| 113 | +// mock never answers. |
| 114 | +func TestAudit_WebSocketInvalidModelRejectedEarly(t *testing.T) { |
| 115 | + llmSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 116 | + w.Write([]byte(`{"choices":[{"message":{"content":"x"}}]}`)) |
| 117 | + })) |
| 118 | + defer llmSrv.Close() |
| 119 | + cleanupEnv := setTestEnv(t, llmSrv.URL) |
| 120 | + defer cleanupEnv() |
| 121 | + |
| 122 | + // Build the store directly under setTestEnv's HOME rather than via |
| 123 | + // newTestSessionStore: that helper captures the *current* HOME (already |
| 124 | + // switched) in its t.Cleanup, so its restore would re-leak this test's |
| 125 | + // temp HOME over setTestEnv's restore and poison every later test's |
| 126 | + // os.UserHomeDir(). setTestEnv's cleanup already scrubs this HOME's |
| 127 | + // .odek/sessions tree. |
| 128 | + store, err := session.NewStore() |
| 129 | + if err != nil { |
| 130 | + t.Fatalf("session.NewStore: %v", err) |
| 131 | + } |
| 132 | + ln, mux := buildServeMux(t, store) |
| 133 | + defer ln.Close() |
| 134 | + go func() { _ = serveOnListener(ln, mux) }() |
| 135 | + waitForHTTP(t, ln.Addr().String()) |
| 136 | + |
| 137 | + wsUpgradeLimiter.reset() |
| 138 | + conn := dialTestWS(t, ln.Addr().String()) |
| 139 | + defer conn.Close() |
| 140 | + |
| 141 | + msg := map[string]string{"type": "prompt", "content": "hi", "model": "BAD MODEL!"} |
| 142 | + payload, _ := json.Marshal(msg) |
| 143 | + if err := golangws.Message.Send(conn, string(payload)); err != nil { |
| 144 | + t.Fatalf("Send(): %v", err) |
| 145 | + } |
| 146 | + |
| 147 | + conn.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 148 | + for i := 0; i < 5; i++ { |
| 149 | + var data []byte |
| 150 | + if err := golangws.Message.Receive(conn, &data); err != nil { |
| 151 | + t.Fatalf("Receive event %d: %v", i, err) |
| 152 | + } |
| 153 | + var evt map[string]any |
| 154 | + if err := json.Unmarshal(data, &evt); err != nil { |
| 155 | + t.Fatalf("unmarshal event %d: %v", i, err) |
| 156 | + } |
| 157 | + if evt["type"] == "error" { |
| 158 | + if got, _ := evt["message"].(string); !strings.Contains(got, "invalid model ID") { |
| 159 | + t.Fatalf("error message = %q, want 'invalid model ID'", got) |
| 160 | + } |
| 161 | + return |
| 162 | + } |
| 163 | + } |
| 164 | + t.Fatal("no invalid-model error event received") |
| 165 | +} |
| 166 | + |
| 167 | +// TestAudit_ResumeTaskPreview pins the Telegram /resume guard: a zero-message |
| 168 | +// session must render an empty preview (the handler then reports "(empty)") |
| 169 | +// instead of panicking on messages[0]. |
| 170 | +func TestAudit_ResumeTaskPreview(t *testing.T) { |
| 171 | + if got := resumeTaskPreview(nil); got != "" { |
| 172 | + t.Errorf("resumeTaskPreview(nil) = %q, want \"\"", got) |
| 173 | + } |
| 174 | + if got := resumeTaskPreview([]llm.Message{}); got != "" { |
| 175 | + t.Errorf("resumeTaskPreview(empty) = %q, want \"\"", got) |
| 176 | + } |
| 177 | + if got := resumeTaskPreview([]llm.Message{{Role: "user", Content: "short task"}}); got != "short task" { |
| 178 | + t.Errorf("resumeTaskPreview(short) = %q, want %q", got, "short task") |
| 179 | + } |
| 180 | + long := strings.Repeat("x", 200) |
| 181 | + got := resumeTaskPreview([]llm.Message{{Role: "user", Content: long}}) |
| 182 | + if runes := len([]rune(got)); runes != 81 || !strings.HasSuffix(got, "…") { |
| 183 | + t.Errorf("resumeTaskPreview(long) = %d runes, want 81 with ellipsis suffix", runes) |
| 184 | + } |
| 185 | +} |
0 commit comments