Restrict chat_sessions to server-owned sessions

chat_sessions now brokers GET /api/session but filters the global list to
the sessions this server recorded in run_steps, deduped by session id, and
fails closed to an empty list when no ownership source is configured. A
session another client holds (in-server claim, released on stream end or
disconnect) or an active run is marked busy; a second client's chat_prompt
for a held session is rejected before any OpenCode call. chat_create stays
unbrokered.
This commit is contained in:
2026-10-16 09:21:50 +01:00
parent dca72a09ee
commit 1818a06d2f
11 changed files with 711 additions and 38 deletions
+186 -12
View File
@@ -2,6 +2,8 @@ package server
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"log"
"strings"
@@ -9,6 +11,7 @@ import (
"time"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
@@ -23,6 +26,9 @@ type chatBroker interface {
Stream(ctx context.Context, sessionID string, ready func(), emit func(protocol.ChatEventFrame) error) error
Interrupt(ctx context.Context, sessionID string) error
Messages(ctx context.Context, sessionID string, limit int) ([]protocol.ChatMessage, error)
// Sessions lists the endpoint's OpenCode sessions so the handler can
// restrict them to the ones this server owns.
Sessions(ctx context.Context) ([]protocol.ChatSession, error)
// Permissions lists the session's pending OpenCode approval requests so the
// handler can push chat_permission frames.
Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error)
@@ -49,6 +55,18 @@ const chatRetainedLimit = opencode.MaxResponse
// least-recently-updated turn is evicted once the cap is exceeded.
const chatMaxTurns = 128
// chatClientToken returns an unguessable per-connection identity. It attributes
// a session claim so two clients on the same server cannot silently write the
// same conversation; a fresh token per connection means a reconnected client is
// a new writer and must re-claim.
func chatClientToken() string {
var b [8]byte
if _, err := rand.Read(b[:]); err != nil {
return "conn-unknown"
}
return "conn-" + hex.EncodeToString(b[:])
}
// chatHub retains the accumulated turn state per session, independently of any
// single connection, so a reconnecting client can re-sync what it missed. State
// is keyed by session and then by message id (a session holds many turns), and
@@ -57,6 +75,10 @@ type chatHub struct {
mu sync.Mutex
turns map[string]*chatTurn
now func() time.Time
// claims maps a session to the client currently writing it so a second
// client is rejected; claimOrder bounds the map like chatMaxTurns.
claims map[string]string
claimOrder []string
}
// chatPart is the retained form of one part. Text and reasoning deltas append to
@@ -223,6 +245,70 @@ func (h *chatHub) evictLocked() {
}
}
// claim reserves sessionID for clientID. It reports true when the session is
// free or already held by the same client (so a client may re-prompt its own
// session) and false when another client holds it. The claim map is bounded by
// chatMaxTurns with oldest-eviction so a stuck client cannot grow it without
// limit.
func (h *chatHub) claim(sessionID, clientID string) bool {
if sessionID == "" || clientID == "" {
return false
}
h.mu.Lock()
defer h.mu.Unlock()
if h.claims == nil {
h.claims = map[string]string{}
}
if holder, ok := h.claims[sessionID]; ok {
return holder == clientID
}
h.evictClaimsLocked()
h.claims[sessionID] = clientID
h.claimOrder = append(h.claimOrder, sessionID)
return true
}
// release drops the same client's claim on sessionID; a claim held by a
// different client is left untouched so a stale release cannot free a live one.
func (h *chatHub) release(sessionID, clientID string) {
h.mu.Lock()
defer h.mu.Unlock()
if holder, ok := h.claims[sessionID]; !ok || holder != clientID {
return
}
delete(h.claims, sessionID)
for i, id := range h.claimOrder {
if id == sessionID {
h.claimOrder = append(h.claimOrder[:i], h.claimOrder[i+1:]...)
break
}
}
}
// busyForOther reports whether another client currently holds sessionID.
func (h *chatHub) busyForOther(sessionID, clientID string) bool {
h.mu.Lock()
defer h.mu.Unlock()
holder, ok := h.claims[sessionID]
return ok && holder != clientID
}
// evictClaimsLocked drops the oldest claim when the cap is reached, keeping the
// claim map bounded like the retained turns. Callers must hold h.mu.
func (h *chatHub) evictClaimsLocked() {
if len(h.claims) < chatMaxTurns {
return
}
for len(h.claimOrder) > 0 {
oldest := h.claimOrder[0]
h.claimOrder = h.claimOrder[1:]
if _, ok := h.claims[oldest]; ok {
delete(h.claims, oldest)
return
}
}
}
// turnLocked returns the session's retained turn, creating it (and evicting the
// least-recently-updated turn first when the cap is reached) and refreshing its
// update time. It is the shared turn-initialization path for apply and
@@ -347,10 +433,10 @@ func (h *chatHub) forgetPermission(sessionID, requestID string) {
// the generic response). Frames are pushed after the ack, each through the
// connection-scoped write function so the read loop and the stream goroutine
// never interleave partial websocket writes.
func handleChat(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, write func(protocol.Message) error) bool {
func handleChat(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, owners func(context.Context) ([]pipeline.SessionOwner, error), clientID string, write func(protocol.Message) error) bool {
switch request.Type {
case protocol.ChatPrompt:
handleChatPrompt(ctx, request, broker, hub, write)
handleChatPrompt(ctx, request, broker, hub, clientID, write)
return true
case protocol.ChatMessages:
handleChatMessages(ctx, request, broker, hub, write)
@@ -361,17 +447,91 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatReply:
handleChatSimple(ctx, request, broker, hub, write)
return true
case protocol.ChatSessions, protocol.ChatCreate:
// Declared in the protocol for the client but not yet brokered. Answer
// explicitly so the client never mistakes the generic Pong for a chat
// reply, and the boundary stays visible instead of silently dropping.
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat_sessions and chat_create are not yet brokered"})
case protocol.ChatSessions:
handleChatSessions(ctx, request, broker, hub, owners, clientID, write)
return true
case protocol.ChatCreate:
// chat_create remains declared for the client but not yet brokered.
// Answer explicitly so the client never mistakes the generic Pong for a
// chat reply, and the boundary stays visible instead of silently
// dropping.
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat_create is not yet brokered"})
return true
}
return false
}
func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, write func(protocol.Message) error) {
// handleChatSessions answers chat_sessions with the OpenCode sessions this
// server owns, marking any another client currently holds (or an active run) as
// Busy. FAIL-CLOSED: when no ownership source is configured the result is empty,
// never the whole endpoint list. broker.Sessions is called at most once per
// request.
func handleChatSessions(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, owners func(context.Context) ([]pipeline.SessionOwner, error), clientID string, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
owned, err := ownedSessionSet(ctx, owners)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
sessions, err := broker.Sessions(ctx)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
response := protocol.Message{Type: protocol.ChatSessions, ID: request.ID}
for _, session := range sessions {
owner, ok := owned[session.ID]
if !ok {
continue
}
if session.Directory == "" {
session.Directory = owner.Directory
}
if owner.Active || hub.busyForOther(session.ID, clientID) {
session.Busy = true
}
response.ChatSessions = append(response.ChatSessions, session)
}
_ = write(response)
}
// ownedSessionSet reads the ownership source once and returns a set keyed by
// session id, deduped in favour of an active owner and a non-empty directory.
// A nil source (no store and no injection) yields an empty set: chat_sessions
// then lists nothing rather than the whole OpenCode machine.
func ownedSessionSet(ctx context.Context, owners func(context.Context) ([]pipeline.SessionOwner, error)) (map[string]pipeline.SessionOwner, error) {
set := map[string]pipeline.SessionOwner{}
if owners == nil {
return set, nil
}
list, err := owners(ctx)
if err != nil {
return nil, err
}
for _, owner := range list {
if owner.ID == "" {
continue
}
existing, ok := set[owner.ID]
if !ok {
set[owner.ID] = owner
continue
}
if owner.Active && !existing.Active {
existing.Active = true
}
if existing.Directory == "" {
existing.Directory = owner.Directory
}
set[owner.ID] = existing
}
return set, nil
}
func handleChatPrompt(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, clientID string, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
@@ -395,12 +555,19 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat prompt exceeds 64 KiB"})
return
}
// Claim the session before subscribing or prompting: a second client must be
// rejected here, before any broker call, so two clients cannot silently write
// the same conversation. The same client may re-prompt its own session.
sessionID := prompt.SessionID
if !hub.claim(sessionID, clientID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is busy with another client"})
return
}
// Subscribe to the OpenCode firehose before posting the prompt: the stream
// has no replay cursor (research 2.4), so a delta emitted between the POST
// and the subscription would otherwise be lost. Frames that arrive before the
// ack is written are buffered and flushed in order after it.
sessionID := prompt.SessionID
streamCtx, streamCancel := context.WithCancel(ctx)
attached := make(chan struct{})
var attachOnce sync.Once
@@ -428,17 +595,20 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
case <-attached:
case err := <-streamResult:
streamCancel()
hub.release(sessionID, clientID)
if err != nil && ctx.Err() == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat stream: " + err.Error()})
}
return
case <-ctx.Done():
streamCancel()
hub.release(sessionID, clientID)
return
}
if err := broker.Prompt(ctx, sessionID, prompt.Text); err != nil {
streamCancel()
hub.release(sessionID, clientID)
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
@@ -446,6 +616,7 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
// reply. The prompt is sent exactly once and never re-sent on resume.
if err := write(protocol.Message{Type: protocol.ChatPrompt, ID: request.ID}); err != nil {
streamCancel()
hub.release(sessionID, clientID)
return
}
// Flush frames buffered while the prompt was accepted, then resume live
@@ -460,11 +631,12 @@ func handleChatPrompt(ctx context.Context, request protocol.Message, broker chat
if err := write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}); err != nil {
bufferMu.Unlock()
streamCancel()
hub.release(sessionID, clientID)
return
}
}
bufferMu.Unlock()
go drainChatStream(ctx, streamResult, streamCancel, sessionID, write)
go drainChatStream(ctx, streamResult, streamCancel, hub, sessionID, clientID, write)
// Poll for pending approval requests alongside the event stream, sharing
// streamCtx so the poller stops when the stream ends or the client
// disconnects. The first poll runs immediately.
@@ -532,9 +704,11 @@ func pushChatPermissions(ctx context.Context, broker chatBroker, hub *chatHub, s
}
// drainChatStream reports the terminal error of a chat subscription and releases
// its context once the stream has ended.
func drainChatStream(ctx context.Context, result <-chan error, cancel context.CancelFunc, sessionID string, write func(protocol.Message) error) {
// its context and the session claim once the stream has ended, so a later client
// is no longer blocked and nothing leaks.
func drainChatStream(ctx context.Context, result <-chan error, cancel context.CancelFunc, hub *chatHub, sessionID, clientID string, write func(protocol.Message) error) {
defer cancel()
defer hub.release(sessionID, clientID)
if err := <-result; err != nil && ctx.Err() == nil {
log.Printf("chat stream session=%s: %v", sessionID, err)
_ = write(protocol.Message{Type: protocol.Error, Error: "chat stream: " + err.Error()})