Merge pull request 'fix(webui): sanitise dashboard chat error responses (#1908)' (#1909) from fix/1908-webui-chat-errors into main
deploy / plan (push) Successful in 46s
deploy / gate (push) Canceled after 0s
deploy / archied-image (push) Canceled after 0s
deploy / agent-image (push) Canceled after 0s
deploy / dist-zip (push) Canceled after 0s
ci/woodpecker/push/deploy Pipeline was canceled

Reviewed-on: #1909
This commit was merged in pull request #1909.
This commit is contained in:
sam committed 2026-11-12 13:23:30 +00:00
commit 779b036d95
2 files changed
+253 -14

No files matched your search

+51 -14
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"path/filepath"
"strings"
@@ -141,6 +142,7 @@ type chatToolView struct {
// waiting for the browser's answer and files a turn offered for download.
type chatAPI struct {
chat *ChatService
log *slog.Logger
updateReportPath string
configSource func() ConfigViewSource
@@ -149,7 +151,7 @@ type chatAPI struct {
}
func newChatAPI(s *Server) *chatAPI {
return &chatAPI{chat: s.Chat, updateReportPath: s.UpdateReportPath, configSource: s.configSource}
return &chatAPI{chat: s.Chat, log: s.Log, updateReportPath: s.UpdateReportPath, configSource: s.configSource}
}
func (a *chatAPI) register(mux *http.ServeMux) {
@@ -173,6 +175,21 @@ func (a *chatAPI) chatReady(w http.ResponseWriter) (*ChatService, bool) {
return a.chat, true
}
// chatFailureText is what the browser sees when a chat backend call fails.
// The cause can carry SQL, gRPC status details or host paths, so failChat
// logs it server-side and sends this sentence instead, in the same plain
// wording the gateway gives chat readers for a failed turn.
const chatFailureText = "something went wrong on Archie's side. Try again; the server log has the cause."
// failChat logs the real cause with the request's trace and answers with the
// plain sentence. A nil logger is tolerated, as tests build servers without one.
func (a *chatAPI) failChat(ctx context.Context, w http.ResponseWriter, status int, err error) {
if a.log != nil {
a.log.ErrorContext(ctx, "chat endpoint failed", "error", err, "status", status)
}
http.Error(w, chatFailureText, status)
}
func chatUpdateServiceConfigured(updates ChatUpdateService) bool {
return !lifecycle.IsNil(updates)
}
@@ -184,7 +201,7 @@ func (a *chatAPI) handleChatSessions(w http.ResponseWriter, r *http.Request) {
}
snapshot, err := chat.Contract.Snapshot(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
out := make([]messaging.SessionContext, 0, len(snapshot.Sessions))
@@ -218,7 +235,7 @@ func (a *chatAPI) handleChatMessages(w http.ResponseWriter, r *http.Request) {
sessionID := r.PathValue("id")
session, found, err := chat.Contract.GetSession(r.Context(), sessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !found || !a.ownsChatSession(r.Context(), session) {
@@ -227,7 +244,7 @@ func (a *chatAPI) handleChatMessages(w http.ResponseWriter, r *http.Request) {
}
messages, err := chat.Contract.RecentMessages(r.Context(), sessionID, 200)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
views := make([]chatMessageView, 0, len(messages))
@@ -249,7 +266,7 @@ func (a *chatAPI) handleChatTurns(w http.ResponseWriter, r *http.Request) {
sessionID := r.PathValue("id")
session, found, err := chat.Contract.GetSession(r.Context(), sessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !found || !a.ownsChatSession(r.Context(), session) {
@@ -258,7 +275,7 @@ func (a *chatAPI) handleChatTurns(w http.ResponseWriter, r *http.Request) {
}
turns, err := chat.Contract.RecentTurns(r.Context(), sessionID, 200)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
views := make([]chatTurnView, 0, len(turns))
@@ -475,7 +492,7 @@ func (a *chatAPI) handleChatStream(w http.ResponseWriter, r *http.Request) {
asker := dashboardAsker{asks: &a.asks, write: func(frame chatStreamEvent) { writeChatEvent(frame, "") }}
events, err := chat.Contract.Stream(withDashboardAsks(r.Context(), asker), msg)
if err != nil {
writeChatEvent(chatStreamEvent{Type: "error", Text: err.Error()}, "")
a.failChatStream(r.Context(), writeChatEvent, err)
return
}
sink := chatStreamSink{showToolCalls: a.chatShowToolCalls(r.Context()), files: &a.files, owner: chatUser(r.Context())}
@@ -492,6 +509,15 @@ func (a *chatAPI) handleChatStream(w http.ResponseWriter, r *http.Request) {
}
}
// failChatStream answers a stream that never opened with the plain sentence
// as its error frame, logging the real cause server-side.
func (a *chatAPI) failChatStream(ctx context.Context, write func(chatStreamEvent, string), err error) {
if a.log != nil {
a.log.ErrorContext(ctx, "chat stream failed to start", "error", err)
}
write(chatStreamEvent{Type: "error", Text: chatFailureText}, "")
}
func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
@@ -499,7 +525,7 @@ func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
}
snapshot, err := chat.Contract.Snapshot(r.Context())
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !snapshot.CancellationAvailable {
@@ -513,7 +539,7 @@ func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
}
session, found, err := chat.Contract.GetSession(r.Context(), req.SessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
if !found || !a.ownsChatSession(r.Context(), session) {
@@ -522,7 +548,7 @@ func (a *chatAPI) handleChatCancel(w http.ResponseWriter, r *http.Request) {
}
result, err := chat.Contract.Cancel(r.Context(), req.SessionID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
a.failChat(r.Context(), w, http.StatusInternalServerError, err)
return
}
writeJSON(w, map[string]any{"cancelled": result.Cancelled, "dropped": result.Dropped})
@@ -538,6 +564,17 @@ func writeUpdateCheckError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadGateway)
}
// failUpdateCheck is the chat endpoints' version of writeUpdateCheckError: any
// other cause can carry registry URLs or host paths, so it gets the plain
// sentence and the log rather than the raw error.
func (a *chatAPI) failUpdateCheck(ctx context.Context, w http.ResponseWriter, err error) {
if errors.Is(err, releaseupdate.ErrNotConfigured) {
http.Error(w, "updates are not configured", http.StatusNotImplemented)
return
}
a.failChat(ctx, w, http.StatusBadGateway, err)
}
func (a *chatAPI) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
chat, ok := a.chatReady(w)
if !ok {
@@ -549,7 +586,7 @@ func (a *chatAPI) handleChatUpdate(w http.ResponseWriter, r *http.Request) {
}
snapshot, err := chat.Updates.Check(r.Context(), 0)
if err != nil {
writeUpdateCheckError(w, err)
a.failUpdateCheck(r.Context(), w, err)
return
}
// The snapshot carries when the installed release was committed on this
@@ -586,7 +623,7 @@ func (a *chatAPI) handleChatUpdateDefer(w http.ResponseWriter, r *http.Request)
return
}
if err := chat.Updates.Defer(r.Context(), 0, req.Snapshot); err != nil {
http.Error(w, err.Error(), http.StatusConflict)
a.failChat(r.Context(), w, http.StatusConflict, err)
return
}
writeJSON(w, map[string]bool{"ok": true})
@@ -608,7 +645,7 @@ func (a *chatAPI) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request
}
fresh, err := chat.Updates.Check(r.Context(), 0)
if err != nil {
writeUpdateCheckError(w, err)
a.failUpdateCheck(r.Context(), w, err)
return
}
if !releaseupdate.SameAvailable(fresh, req.Snapshot) {
@@ -633,7 +670,7 @@ func (a *chatAPI) handleChatUpdateInstall(w http.ResponseWriter, r *http.Request
meta := releaseupdate.InstallMeta{Channel: "webui", ReportPath: a.updateReportPath}
result, err := chat.Updates.Install(r.Context(), fresh, meta, func(message string) { progress = append(progress, message) })
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
a.failChat(r.Context(), w, http.StatusBadGateway, err)
return
}
writeJSON(w, map[string]any{"ok": true, "progress": progress, "result": result})
+202
View File
@@ -0,0 +1,202 @@
package webui
import (
"bytes"
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
// internalDetail stands in for the SQL fragments, gRPC status details and host
// paths a real contract failure carries; none of it may reach the browser.
const internalDetail = `pq: relation "chat_messages" does not exist: SELECT * FROM chat_messages WHERE session_id=$1 (/var/lib/archie/state.db): rpc error: code = Internal desc = session store unavailable`
var errInternal = errors.New(internalDetail)
// plainChatFailure is the sentence the browser must see instead; spelled out
// here so the test also compiles, and fails, against the unsanitised handlers.
const plainChatFailure = "something went wrong on Archie's side. Try again; the server log has the cause."
// failingChat fails the contract methods its fields name, so one fake covers
// every chat endpoint.
type failingChat struct {
messaging.ChatContract
snapshotErr, sessionErr, messagesErr, turnsErr, cancelErr, streamErr error
}
func (f failingChat) Snapshot(context.Context) (messaging.ChatSnapshot, error) {
if f.snapshotErr != nil {
return messaging.ChatSnapshot{}, f.snapshotErr
}
return messaging.ChatSnapshot{CancellationAvailable: true}, nil
}
func (f failingChat) GetSession(context.Context, string) (messaging.SessionContext, bool, error) {
if f.sessionErr != nil {
return messaging.SessionContext{}, false, f.sessionErr
}
return messaging.SessionContext{SessionID: "s1", Source: messaging.SessionSource{Platform: "web", ThreadID: "alice"}}, true, nil
}
func (f failingChat) RecentMessages(context.Context, string, int) ([]messaging.Message, error) {
if f.messagesErr != nil {
return nil, f.messagesErr
}
return []messaging.Message{}, nil
}
func (f failingChat) RecentTurns(context.Context, string, int) ([]messaging.TurnRecord, error) {
if f.turnsErr != nil {
return nil, f.turnsErr
}
return []messaging.TurnRecord{}, nil
}
func (f failingChat) Stream(context.Context, messaging.Inbound) (<-chan messaging.ChatEvent, error) {
return nil, f.streamErr
}
func (f failingChat) Cancel(context.Context, string) (messaging.ChatCancellation, error) {
if f.cancelErr != nil {
return messaging.ChatCancellation{}, f.cancelErr
}
return messaging.ChatCancellation{Cancelled: true}, nil
}
type failingUpdates struct {
ChatUpdateService
err error
}
func (f failingUpdates) Check(context.Context, int64) (releaseupdate.Snapshot, error) {
return releaseupdate.Snapshot{}, f.err
}
func chatErrorRequest(t *testing.T, method, target, body string) *http.Request {
t.Helper()
ctx := WithActingIdentity(t.Context(), identity.Identity{ID: identity.IdentityID("alice")})
req := httptest.NewRequestWithContext(ctx, method, target, strings.NewReader(body))
req.SetPathValue("id", "s1")
return req
}
func assertSanitised(t *testing.T, body, log string) {
t.Helper()
if strings.Contains(body, internalDetail) {
t.Errorf("response leaks the internal error: %s", body)
}
for _, fragment := range []string{"pq:", "chat_messages", "/var/lib", "rpc error"} {
if strings.Contains(body, fragment) {
t.Errorf("response leaks internal fragment %q: %s", fragment, body)
}
}
if !strings.Contains(body, plainChatFailure) {
t.Errorf("response is missing the plain message, got: %s", body)
}
if !strings.Contains(log, "session store unavailable") {
t.Errorf("the real error was not logged server-side, log: %s", log)
}
}
func TestChatEndpointErrorsAreSanitised(t *testing.T) {
for _, tc := range []struct {
name string
contract failingChat
handler func(*chatAPI, http.ResponseWriter, *http.Request)
body string
wantStatus int
}{
{"sessions snapshot", failingChat{snapshotErr: errInternal}, (*chatAPI).handleChatSessions, "", http.StatusInternalServerError},
{"messages session lookup", failingChat{sessionErr: errInternal}, (*chatAPI).handleChatMessages, "", http.StatusInternalServerError},
{"messages history", failingChat{messagesErr: errInternal}, (*chatAPI).handleChatMessages, "", http.StatusInternalServerError},
{"turns session lookup", failingChat{sessionErr: errInternal}, (*chatAPI).handleChatTurns, "", http.StatusInternalServerError},
{"turns history", failingChat{turnsErr: errInternal}, (*chatAPI).handleChatTurns, "", http.StatusInternalServerError},
{"cancel snapshot", failingChat{snapshotErr: errInternal}, (*chatAPI).handleChatCancel, `{"session_id":"s1"}`, http.StatusInternalServerError},
{"cancel session lookup", failingChat{sessionErr: errInternal}, (*chatAPI).handleChatCancel, `{"session_id":"s1"}`, http.StatusInternalServerError},
{"cancel call", failingChat{cancelErr: errInternal}, (*chatAPI).handleChatCancel, `{"session_id":"s1"}`, http.StatusInternalServerError},
} {
t.Run(tc.name, func(t *testing.T) {
var logBuf bytes.Buffer
srv := &Server{Log: slog.New(slog.NewTextHandler(&logBuf, nil)), Chat: &ChatService{Contract: tc.contract}}
rec := httptest.NewRecorder()
tc.handler(newChatAPI(srv), rec, chatErrorRequest(t, "POST", "https://archie.example/api/chat/x", tc.body))
if rec.Code != tc.wantStatus {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tc.wantStatus, rec.Body.String())
}
assertSanitised(t, rec.Body.String(), logBuf.String())
})
}
}
func TestChatStreamErrorFrameIsSanitised(t *testing.T) {
var logBuf bytes.Buffer
srv := &Server{Log: slog.New(slog.NewTextHandler(&logBuf, nil)), Chat: &ChatService{Contract: failingChat{streamErr: errInternal}}}
rec := httptest.NewRecorder()
req := chatErrorRequest(t, "POST", "https://archie.example/api/chat/stream", `{"channel_id":"c","text":"hi"}`)
newChatAPI(srv).handleChatStream(rec, req)
body := rec.Body.String()
if !strings.Contains(body, `"type":"error"`) {
t.Fatalf("no error frame in stream: %s", body)
}
assertSanitised(t, body, logBuf.String())
}
func TestChatUpdateCheckErrorIsSanitised(t *testing.T) {
for _, tc := range []struct {
name string
err error
wantStatus int
wantBody string
}{
{"internal cause", errInternal, http.StatusBadGateway, plainChatFailure},
{"not configured", releaseupdate.ErrNotConfigured, http.StatusNotImplemented, "updates are not configured"},
} {
t.Run(tc.name, func(t *testing.T) {
var logBuf bytes.Buffer
srv := &Server{Log: slog.New(slog.NewTextHandler(&logBuf, nil)), Chat: &ChatService{Contract: failingChat{}, Updates: failingUpdates{err: tc.err}}}
rec := httptest.NewRecorder()
newChatAPI(srv).handleChatUpdate(rec, chatErrorRequest(t, "GET", "https://archie.example/api/chat/update", ""))
if rec.Code != tc.wantStatus {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tc.wantStatus, rec.Body.String())
}
if got := strings.TrimSpace(rec.Body.String()); got != tc.wantBody {
t.Fatalf("body=%q want=%q", got, tc.wantBody)
}
if errors.Is(tc.err, errInternal) {
assertSanitised(t, rec.Body.String(), logBuf.String())
}
})
}
}
func TestChatValidationMessagesStayUserFacing(t *testing.T) {
for _, tc := range []struct {
name, body, want string
}{
{"missing fields", `{"channel_id":"","text":""}`, "text and channel_id are required"},
{"undecodable", `{`, "invalid chat message"},
{"empty voice", `{"channel_id":"c","text":"hi","voice":{"data":"","mime_type":"audio/ogg"}}`, "voice clip is empty or too long"},
} {
t.Run(tc.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := chatErrorRequest(t, "POST", "https://archie.example/api/chat/stream", tc.body)
if _, ok := newChatAPI(&Server{}).decodeChatMessage(rec, req); ok {
t.Fatal("message accepted")
}
if rec.Code != http.StatusBadRequest {
t.Fatalf("status=%d want=400", rec.Code)
}
if got := strings.TrimSpace(rec.Body.String()); got != tc.want {
t.Fatalf("body=%q want=%q", got, tc.want)
}
})
}
}