From 40bcd1cd1369b4e331a7ceb80d5c13ded566d25e Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 18:05:35 +0100 Subject: [PATCH 1/3] fix(api): a device can't name the user the agent joins and writes Chat as createSession and the socket's start frame copied a device's user_id, user_name and agent_id into the session spec. The router then minted a token for that user id, joined the call as it, and created the conversation channel and wrote the agent's messages as agent_id, with its own server credentials. A user's device could make the agent write as any other user of the app. refuseSessionRequest now refuses, from an end user's device: - agent_id, any value; - user_id, unless it is the default (vision-agent) or the caller's own verified user id; - user_name, unless it is the default (Vision Agent). A backend sends them as before. The defaults stay allowed because generated clients (Swift) fill them in. Co-Authored-By: Claude Opus 5.5 --- .../internal/api/dispatch_channel_test.go | 28 ++--- acceleration/internal/api/session_create.go | 42 +++++++ .../api/session_identity_unit_test.go | 78 ++++++++++++ acceleration/internal/api/socketws_test.go | 16 +++ .../internal/api/thread_access_test.go | 112 ++++++++---------- acceleration/internal/session/session.go | 7 ++ 6 files changed, 206 insertions(+), 77 deletions(-) create mode 100644 acceleration/internal/api/session_identity_unit_test.go diff --git a/acceleration/internal/api/dispatch_channel_test.go b/acceleration/internal/api/dispatch_channel_test.go index fd8f85d4c0..b545b908eb 100644 --- a/acceleration/internal/api/dispatch_channel_test.go +++ b/acceleration/internal/api/dispatch_channel_test.go @@ -96,22 +96,19 @@ func (s *MessageHooksSuite) TestAnotherPersonsMessageIsAnsweredByTheWorkersSessi } // TestOnlyTheBackendOfTheChannelsCustomerOpensItsChannel: a session another customer's -// backend, the customer's own end user, or its backend acting for one of its users opens -// under the channel's id keeps a channel of its own, as on base. +// backend, or the customer's backend acting for one of its users, opens under the channel's +// id keeps a channel of its own, as on base. The customer's own end user names no agent id. func (s *MessageHooksSuite) TestOnlyTheBackendOfTheChannelsCustomerOpensItsChannel() { handed := s.handedOut() owner := s.app asked := CreateSessionRequest{AgentId: &handed.AgentID, Llm: pointerTo("en-low-latency")} - for name, opener := range map[string]*testClient{ - "end user": s.client, - "backend acting for a user": s.serverClient.actingFor(s.client), - } { - opened := opener.createSession(asked) - s.Equal(chatlog.ChannelType+":"+opened.Id, value(opened.ConversationId), name) - } + status, body := s.client.call(http.MethodPost, "/v1/agents/sessions", asked) + s.Equal(http.StatusForbidden, status, "end user: %s", body) + opened := s.serverClient.actingFor(s.client).createSession(asked) + s.Equal(chatlog.ChannelType+":"+opened.Id, value(opened.ConversationId), "backend acting for a user") s.useApp(s.data.createApp()) - opened := s.serverClient.createSession(asked) + opened = s.serverClient.createSession(asked) s.Equal(chatlog.ChannelType+":"+opened.Id, value(opened.ConversationId), "another customer") s.useApp(owner) } @@ -220,13 +217,14 @@ func (s *MessageHooksSuite) TestAWorkersQuestionAskedAgainIsAnsweredOnce() { // (probe in the PR's author log). func (s *MessageHooksSuite) TestACommandToASessionOfItsOwnStillWritesThePersonsMessage() { for name, opener := range map[string]struct { - client *testClient - author string + client *testClient + author string + agentID *string }{ - "a backend's session": {s.serverClient, "support-operator"}, - "an end user's session": {s.client, s.client.userID}, + "a backend's session": {s.serverClient, "support-operator", pointerTo("agent-" + s.utils.uuid())}, + "an end user's session": {s.client, s.client.userID, nil}, } { - opened := opener.client.createSession(CreateSessionRequest{AgentId: pointerTo("agent-" + s.utils.uuid()), Llm: pointerTo("en-low-latency")}) + opened := opener.client.createSession(CreateSessionRequest{AgentId: opener.agentID, Llm: pointerTo("en-low-latency")}) s.Require().Equal(chatlog.ChannelType+":"+opened.Id, value(opened.ConversationId), name) watching := opener.client.opens("/v1/agents/sessions/" + opened.Id + "/events") id := s.utils.uuid() diff --git a/acceleration/internal/api/session_create.go b/acceleration/internal/api/session_create.go index 982360081a..1e9e9cabe7 100644 --- a/acceleration/internal/api/session_create.go +++ b/acceleration/internal/api/session_create.go @@ -156,6 +156,45 @@ var errDeviceMemoryUser = forbidden("memory.user_id is sent server-side unless i var errAnonymousMemory = forbidden("memory needs a signed-in user: an anonymous caller's name is a claim " + "nobody checked, so the memories kept under it could be anyone's") +// errDeviceAgentUser refuses an end user's device naming the user the agent joins and writes as. +var errDeviceAgentUser = forbidden("user_id is sent server-side unless it is the default " + + session.DefaultUserID + " or the caller's own user id: the agent joins the call and writes " + + "Chat messages as the user it names, which a device may not choose for somebody else") + +// errDeviceAgentUserName refuses an end user's device naming the agent's display name. +var errDeviceAgentUserName = forbidden("user_name is sent server-side unless it is the default " + + session.DefaultUserName + ": it is stored as the name of the Chat user the agent writes as, " + + "which a device may not rename") + +// errDeviceAgentID refuses an agent id named by an end user's device. +var errDeviceAgentID = forbidden("agent_id is sent server-side: the agent's Chat messages and the " + + "channel it keeps are written as it, which a device may not choose") + +// refuseDeviceAgentIdentity reports the failure a new session is refused with when an end +// user's device names who the agent is. The router's own credentials act as that identity, +// so a device may only ask for the default, or, for user_id, its own verified user id. +// +// Why: generated clients fill in the schema defaults for user_id and user_name, so a device +// sending exactly those is let through rather than refused. +func refuseDeviceAgentIdentity(ctx context.Context, request CreateSessionRequest) (APIError, bool) { + if ServerSideFrom(ctx) { + return APIError{}, false + } + if id := value(request.AgentId); id != "" { + return errDeviceAgentID, true + } + if user := value(request.UserId); user != "" && user != session.DefaultUserID { + caller := CallerFrom(ctx).UserID + if !KindFrom(ctx).Verified() || caller == "" || user != caller { + return errDeviceAgentUser, true + } + } + if name := value(request.UserName); name != "" && name != session.DefaultUserName { + return errDeviceAgentUserName, true + } + return APIError{}, false +} + // refuseSessionRequest reports the failure a new session's request is refused with before // anything is made for it. createSession and the session socket both call it, so a request one // of them refuses the other refuses too, with the same error. @@ -163,6 +202,9 @@ func refuseSessionRequest(ctx context.Context, request CreateSessionRequest) (AP if failure, refused := refuseServerSideFields(ctx, request); refused { return failure, true } + if failure, refused := refuseDeviceAgentIdentity(ctx, request); refused { + return failure, true + } // The same rules as createAuthorization's, since it is the same attempt that seals it. if returnURL := value(request.ReturnUrl); returnURL != "" { if err := checkReturnURL(returnURL); err != nil { diff --git a/acceleration/internal/api/session_identity_unit_test.go b/acceleration/internal/api/session_identity_unit_test.go new file mode 100644 index 0000000000..8ac91ec1e3 --- /dev/null +++ b/acceleration/internal/api/session_identity_unit_test.go @@ -0,0 +1,78 @@ +package api + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/GetStream/Vision-Agents/acceleration/internal/auth" + "github.com/GetStream/Vision-Agents/acceleration/internal/routing" + "github.com/GetStream/Vision-Agents/acceleration/internal/session" +) + +// deviceAsking is an end user's device of the given kind, going by userID. +func deviceAsking(kind auth.Kind, userID string) context.Context { + ctx := context.WithValue(context.Background(), kindContextKey{}, kind) + return routing.WithCaller(ctx, routing.Caller{UserID: userID}) +} + +func TestADeviceMayNotNameAnotherUserForTheAgentToJoinAndWriteAs(t *testing.T) { + for _, kind := range []auth.Kind{auth.KindAuthenticated, auth.KindGuest, auth.KindAnonymous} { + failure, refused := refuseSessionRequest(deviceAsking(kind, "alice"), CreateSessionRequest{UserId: new("bob")}) + + require.True(t, refused, string(kind)) + require.Equal(t, errDeviceAgentUser, failure, string(kind)) + } +} + +func TestAnAnonymousCallerMayNotNameItsOwnClaimedIdForTheAgent(t *testing.T) { + failure, refused := refuseSessionRequest(deviceAsking(auth.KindAnonymous, "bob"), CreateSessionRequest{UserId: new("bob")}) + + require.True(t, refused, "an anonymous caller's name is a claim nobody checked") + require.Equal(t, errDeviceAgentUser, failure) +} + +func TestASignedInDeviceMayNameItsOwnUserIdForTheAgent(t *testing.T) { + for _, kind := range []auth.Kind{auth.KindAuthenticated, auth.KindGuest} { + _, refused := refuseSessionRequest(deviceAsking(kind, "alice"), CreateSessionRequest{UserId: new("alice")}) + + require.False(t, refused, string(kind)) + } +} + +func TestADeviceMayNotNameTheAgentsId(t *testing.T) { + for _, kind := range []auth.Kind{auth.KindAuthenticated, auth.KindGuest, auth.KindAnonymous} { + failure, refused := refuseSessionRequest(deviceAsking(kind, "alice"), CreateSessionRequest{AgentId: new("alice")}) + + require.True(t, refused, string(kind)) + require.Equal(t, errDeviceAgentID, failure, string(kind)) + } +} + +func TestADeviceMayNotRenameTheAgentsChatUser(t *testing.T) { + failure, refused := refuseSessionRequest(deviceAsking(auth.KindAuthenticated, "alice"), + CreateSessionRequest{UserName: new("Your Bank")}) + + require.True(t, refused) + require.Equal(t, errDeviceAgentUserName, failure) +} + +// Generated clients fill in the schema defaults, so a device that sends them is let through. +func TestADeviceSendingTheDefaultAgentIdentityIsLetThrough(t *testing.T) { + sent := CreateSessionRequest{ + UserId: new(session.DefaultUserID), UserName: new(session.DefaultUserName), AgentId: new(""), + } + for _, kind := range []auth.Kind{auth.KindAuthenticated, auth.KindGuest, auth.KindAnonymous} { + _, refused := refuseSessionRequest(deviceAsking(kind, "alice"), sent) + + require.False(t, refused, string(kind)) + } +} + +func TestABackendNamesAnyAgentIdentity(t *testing.T) { + _, refused := refuseSessionRequest(backendAsking(), + CreateSessionRequest{UserId: new("support-bot"), UserName: new("Support"), AgentId: new("support")}) + + require.False(t, refused) +} diff --git a/acceleration/internal/api/socketws_test.go b/acceleration/internal/api/socketws_test.go index 5810ed5506..9949ebaf18 100644 --- a/acceleration/internal/api/socketws_test.go +++ b/acceleration/internal/api/socketws_test.go @@ -200,6 +200,22 @@ func (s *SocketSessionSuite) TestADeviceMayNotHandTheSocketAServerSideField() { } } +// The router's credentials act as whoever a session names the agent, so neither createSession +// nor the socket lets a device name another user, an agent id or a display name for it. +func (s *SocketSessionSuite) TestADeviceMayNotHandTheSocketAnotherAgentIdentity() { + for _, device := range []*testClient{s.client, s.guestClient, s.anonymousClient} { + s.Run("user_id/"+string(device.kind), func() { + s.assertSocketRefuses(device, map[string]any{"user_id": "someone-else"}, errDeviceAgentUser) + }) + s.Run("agent_id/"+string(device.kind), func() { + s.assertSocketRefuses(device, map[string]any{"agent_id": "support"}, errDeviceAgentID) + }) + s.Run("user_name/"+string(device.kind), func() { + s.assertSocketRefuses(device, map[string]any{"user_name": "Your Bank"}, errDeviceAgentUserName) + }) + } +} + // assertSocketRefuses checks a device's start frame is refused as its create was, and that // both say the field's own refusal rather than another field's. func (s *SocketSessionSuite) assertSocketRefuses(device *testClient, sent map[string]any, refusal APIError) { diff --git a/acceleration/internal/api/thread_access_test.go b/acceleration/internal/api/thread_access_test.go index 01c445d690..983eb49360 100644 --- a/acceleration/internal/api/thread_access_test.go +++ b/acceleration/internal/api/thread_access_test.go @@ -24,36 +24,31 @@ import ( // Who may name a thread channel. Only the customer's backend, or the Router's own message // hook (threadhooks.go), holds a session on one. An end user's device naming one, by its // agent id or by any other way into a session, is answered exactly as for an id no thread -// channel has, so nothing it is told says the thread exists. The tests below compare the +// channel has, so nothing it is told says the thread exists. A device names no agent id at +// all (errDeviceAgentID), so by its agent id it is refused alike. The tests below compare the // two answers; SlackChannelSuite's own tests are the backend and the hook still working. -// TestADeviceNamingAThreadChannelsAgentIDKeepsAConversationOfItsOwn: a device's text session -// under a thread channel's agent id keeps a support channel of its own, as one under an agent -// id no thread channel has does. -func (s *SlackChannelSuite) TestADeviceNamingAThreadChannelsAgentIDKeepsAConversationOfItsOwn() { +// TestADeviceNamingAThreadChannelsAgentIDIsRefusedAsForAnUnknownOne: a device's text session +// under a thread channel's agent id is refused exactly as one under an agent id no thread +// channel has. +func (s *SlackChannelSuite) TestADeviceNamingAThreadChannelsAgentIDIsRefusedAsForAnUnknownOne() { channel := s.messaged("U0000ALICE", "is the build green?", "1759740000.000100", "") unknown := conversation.ThreadChannelPrefix + s.utils.uuid() - named := s.client.createSession(CreateSessionRequest{Agent: &s.config.Name, AgentId: &channel}) - guessed := s.client.createSession(CreateSessionRequest{Agent: &s.config.Name, AgentId: &unknown}) - - s.Equal(answeredFor(guessed, unknown), answeredFor(named, channel)) - s.Equal(channel, named.AgentId) - s.Equal("agent:"+named.Id, value(named.ConversationId), "the conversation is the device's own, not the thread channel") + s.refusedAlike(CreateSessionRequest{Agent: &s.config.Name, AgentId: &channel}, + CreateSessionRequest{Agent: &s.config.Name, AgentId: &unknown}) } -// TestTheThreadIsAnsweredByTheRouterNotByADevicesSessionNamingIt: the person's message in the -// thread is answered by the Router's own session, into the Slack thread, and never reaches -// the session a device opened under the thread channel's agent id. +// TestTheThreadIsAnsweredByTheRouterNotByADevicesSessionNamingIt: a device asking for a +// session under the thread channel's agent id is refused, and the person's message in the +// thread is still answered by the Router's own session, into the Slack thread. func (s *SlackChannelSuite) TestTheThreadIsAnsweredByTheRouterNotByADevicesSessionNamingIt() { channel := s.messaged("U0000ALICE", "is the build green?", "1759740000.000100", "") - mine := s.client.createSession(CreateSessionRequest{Agent: &s.config.Name, AgentId: &channel}) + s.refused(CreateSessionRequest{Agent: &s.config.Name, AgentId: &channel}) s.Require().Equal(http.StatusOK, s.streamDelivers(channel, 0)) s.Equal("Noted.", s.posted(1)[0].Text, "the reply leaves into the Slack thread") - own := strings.TrimPrefix(value(mine.ConversationId), "agent:") - s.Empty(s.chat.Stored(own), "nothing of the thread reaches the device's conversation") } // TestTheBackendsSessionOnAThreadChannelAnswersTheThread: the turn the inbound worker hands @@ -70,17 +65,15 @@ func (s *SlackChannelSuite) TestTheBackendsSessionOnAThreadChannelAnswersTheThre s.Nil(s.serverClient.getSession(held.Id).ClosedAt, "the backend's session answered and is still running") } -// TestADevicesCallNamingAThreadChannelWritesNoTranscriptThere: a voice transcript is written -// into the session's own channel (chatlog.Options.Channel), never the one its agent id names. +// TestADevicesCallNamingAThreadChannelWritesNoTranscriptThere: a device's call under a thread +// channel's agent id is refused as one under an unknown agent id, and writes nothing there. func (s *SlackChannelSuite) TestADevicesCallNamingAThreadChannelWritesNoTranscriptThere() { channel := s.messaged("U0000ALICE", "is the build green?", "1759740000.000100", "") unknown := conversation.ThreadChannelPrefix + s.utils.uuid() - named := s.client.createSession(CreateSessionRequest{AgentId: &channel, StartVoice: pointerTo(true)}) - guessed := s.client.createSession(CreateSessionRequest{AgentId: &unknown, StartVoice: pointerTo(true)}) + s.refusedAlike(CreateSessionRequest{AgentId: &channel, StartVoice: pointerTo(true)}, + CreateSessionRequest{AgentId: &unknown, StartVoice: pointerTo(true)}) - s.Equal(answeredFor(guessed, unknown), answeredFor(named, channel)) - s.True(s.transcribed.opened(value(guessed.ConversationId)), "the session's own channel holds the transcript") s.False(s.transcribed.opened(chatlog.ChannelType+":"+channel), "the thread channel holds no transcript of the device's call") } @@ -89,11 +82,9 @@ func (s *SlackChannelSuite) TestADevicesCallNamingAThreadChannelsAgentIDInUpperC channel := s.messaged("U0000ALICE", "is the build green?", "1759740000.000100", "") upper, unknown := strings.ToUpper(channel), strings.ToUpper(conversation.ThreadChannelPrefix+s.utils.uuid()) - named := s.client.createSession(CreateSessionRequest{AgentId: &upper, StartVoice: pointerTo(true)}) - guessed := s.client.createSession(CreateSessionRequest{AgentId: &unknown, StartVoice: pointerTo(true)}) + s.refusedAlike(CreateSessionRequest{AgentId: &upper, StartVoice: pointerTo(true)}, + CreateSessionRequest{AgentId: &unknown, StartVoice: pointerTo(true)}) - s.Equal(answeredFor(guessed, unknown), answeredFor(named, upper)) - s.True(s.transcribed.opened(value(guessed.ConversationId)), "the session's own channel holds the transcript") s.False(s.transcribed.opened(chatlog.ChannelType+":"+upper), "the thread channel's id in upper case holds no transcript") } @@ -104,11 +95,9 @@ func (s *SlackChannelSuite) TestADevicesCallNamingAThreadChannelsAgentIDWithALea channel := s.messaged("U0000ALICE", "is the build green?", "1759740000.000100", "") padded, unknown := " "+channel, " "+conversation.ThreadChannelPrefix+s.utils.uuid() - named := s.client.createSession(CreateSessionRequest{AgentId: &padded, StartVoice: pointerTo(true)}) - guessed := s.client.createSession(CreateSessionRequest{AgentId: &unknown, StartVoice: pointerTo(true)}) + s.refusedAlike(CreateSessionRequest{AgentId: &padded, StartVoice: pointerTo(true)}, + CreateSessionRequest{AgentId: &unknown, StartVoice: pointerTo(true)}) - s.Equal(answeredFor(guessed, unknown), answeredFor(named, padded)) - s.True(s.transcribed.opened(value(guessed.ConversationId)), "the session's own channel holds the transcript") s.False(s.transcribed.opened(chatlog.ChannelType+":"+padded), "the padded thread channel id holds no transcript") } @@ -131,7 +120,7 @@ func (s *SlackChannelSuite) TestADevicesCallIsBarredFromAChannelWhoseThreadLinkC channel := s.messaged("U0000ALICE", "is the build green?", "1759740000.000100", "") s.unreadableLink(channel) - s.client.createSession(CreateSessionRequest{AgentId: &channel, StartVoice: pointerTo(true)}) + s.refused(CreateSessionRequest{AgentId: &channel, StartVoice: pointerTo(true)}) s.False(s.transcribed.opened(chatlog.ChannelType + ":" + channel)) } @@ -143,7 +132,7 @@ func (s *SlackChannelSuite) TestAMessageInAChannelWhoseThreadLinkCannotBeReadIsA said := "and the deploy? " + s.utils.uuid() channel := s.answeredThread() s.unreadableLink(channel) - s.client.createSession(CreateSessionRequest{Agent: &s.config.Name, AgentId: &channel, StartVoice: pointerTo(true)}) + s.refused(CreateSessionRequest{Agent: &s.config.Name, AgentId: &channel, StartVoice: pointerTo(true)}) s.sentInThread(channel, said) @@ -168,13 +157,11 @@ func (s *SlackChannelSuite) TestADevicesSocketNamingAThreadChannelWritesNoTransc channel := s.messaged("U0000ALICE", "is the build green?", "1759740000.000100", "") unknown := conversation.ThreadChannelPrefix + s.utils.uuid() - named := s.socketSession(channel) - guessed := s.socketSession(unknown) + named := s.socketRefusal(channel) + guessed := s.socketRefusal(unknown) - s.Equal(channel, named["agent_id"]) - s.Equal(unknown, guessed["agent_id"]) - s.Equal(guessed["state"], named["state"]) - s.True(s.transcribed.opened(guessed["conversation_id"].(string)), "the session's own channel holds the transcript") + s.Equal(errDeviceAgentID.Message, named["error"]) + s.Equal(guessed, named) s.False(s.transcribed.opened(chatlog.ChannelType+":"+channel), "the thread channel holds no transcript of the device's socket") } @@ -338,18 +325,15 @@ func (s *SlackChannelSuite) TestABackendOpensAThreadChannelAgainByItsAgentID() { s.Equal("agent:"+channel, value(again.ConversationId)) } -// TestWithNoThreadLinkedADevicesAgentIDIsAnsweredAsBefore: with no channel_threads row, as -// staging runs with connectors off, an agent id in the thread- namespace is any agent id: a -// conversation of its own, and a call's transcript in its own channel too. -func (s *SlackChannelSuite) TestWithNoThreadLinkedADevicesAgentIDIsAnsweredAsBefore() { +// TestWithNoThreadLinkedADevicesAgentIDIsRefusedAsAnyOther: with no channel_threads row, as +// staging runs with connectors off, an agent id in the thread- namespace is any agent id, +// which a device does not name, and no thread channel is opened for it. +func (s *SlackChannelSuite) TestWithNoThreadLinkedADevicesAgentIDIsRefusedAsAnyOther() { texted, called := conversation.ThreadChannelPrefix+s.utils.uuid(), conversation.ThreadChannelPrefix+s.utils.uuid() - text := s.client.createSession(CreateSessionRequest{Agent: &s.config.Name, AgentId: &texted}) - call := s.client.createSession(CreateSessionRequest{AgentId: &called, StartVoice: pointerTo(true)}) + s.refused(CreateSessionRequest{Agent: &s.config.Name, AgentId: &texted}) + s.refused(CreateSessionRequest{AgentId: &called, StartVoice: pointerTo(true)}) - s.Equal(texted, text.AgentId) - s.Equal("agent:"+text.Id, value(text.ConversationId)) - s.True(s.transcribed.opened(value(call.ConversationId))) s.Zero(s.threadChannels()) } @@ -519,29 +503,33 @@ func (s *SlackChannelSuite) TestAHookStartedReplyIsMarkedHookChat() { } } -// answeredFor is what a created session says of itself that does not differ by its ids: the -// agent id it was asked for, the sort of conversation it keeps, its state and modality. -func answeredFor(opened Session, agentID string) []any { - return []any{opened.AgentId == agentID, value(opened.ConversationId) == "agent:"+opened.Id, - opened.State, opened.Modality} +// refused checks a device asking for a session as asked is refused for naming an agent id, +// and returns the message it was refused with. +func (s *SlackChannelSuite) refused(asked CreateSessionRequest) string { + status, body := s.client.call(http.MethodPost, "/v1/agents/sessions", asked) + s.Require().Equal(http.StatusForbidden, status, string(body)) + var answered ErrorResponse + s.Require().NoError(json.Unmarshal(body, &answered)) + s.Require().Equal(errDeviceAgentID.Message, answered.Error.Message) + return answered.Error.Message } -// socketSession opens a device's voice socket session under agentID and returns the session -// it was answered with. -func (s *SlackChannelSuite) socketSession(agentID string) map[string]any { - return s.socketSessionWith(map[string]any{"agent_id": agentID}) +// refusedAlike checks a device naming a thread channel is refused exactly as one naming an id +// no thread channel has. +func (s *SlackChannelSuite) refusedAlike(named, guessed CreateSessionRequest) { + s.Equal(s.refused(guessed), s.refused(named)) } -// socketSessionWith opens a device's voice socket session asked for as asked. -func (s *SlackChannelSuite) socketSessionWith(asked map[string]any) map[string]any { +// socketRefusal is the frame a device's voice socket is refused with when it names agentID. +func (s *SlackChannelSuite) socketRefusal(agentID string) map[string]any { connection := s.client.opens("/v1/agents/socket") s.Require().NoError(connection.WriteJSON(map[string]any{ - "type": "start", "sample_rate": 24_000, "session": asked, + "type": "start", "sample_rate": 24_000, "session": map[string]any{"agent_id": agentID}, })) var answered map[string]any s.Require().NoError(connection.ReadJSON(&answered)) - s.Require().Equal("session", answered["type"], "the socket answered %v", answered) - return answered["session"].(map[string]any) + s.Require().Equal("error", answered["type"], "the socket answered %v", answered) + return answered } // openedTranscripts keeps the channel each voice session's transcript was opened for, named diff --git a/acceleration/internal/session/session.go b/acceleration/internal/session/session.go index 510c529c3b..5feee6891b 100644 --- a/acceleration/internal/session/session.go +++ b/acceleration/internal/session/session.go @@ -42,6 +42,13 @@ import ( // reader some detail and nobody on the call anything. const watcherBuffer = 256 +// DefaultUserID and DefaultUserName are who the agent joins a call and writes Chat as when +// nobody names it: the only identity an end user's device may ask for by name. +const ( + DefaultUserID = defaultUserID + DefaultUserName = defaultUserName +) + // Defaults a caller can leave out. They are the same ones cmd/agent's flags carry, so a // session started with an almost empty spec behaves like the demo. const ( From 787f77856db8520ca050eba49a3b16b860893032 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 18:13:10 +0100 Subject: [PATCH 2/3] test(api): a device's hosted call reaches the worker through its config, not an agent id Co-Authored-By: Claude Opus 5.5 --- .../internal/api/chat_channels_hosted_test.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/acceleration/internal/api/chat_channels_hosted_test.go b/acceleration/internal/api/chat_channels_hosted_test.go index 4c7b251f31..49c0177b22 100644 --- a/acceleration/internal/api/chat_channels_hosted_test.go +++ b/acceleration/internal/api/chat_channels_hosted_test.go @@ -76,12 +76,14 @@ func (s *RouterSuite) hostedCallUser(worker *websocket.Conn) any { // The control: a session a person opened with their own token names them on a hosted call, as // on base b466fb795 (probe of this test there). func (s *SessionToolsSuite) TestAHostedCallInASessionOpenedWithAUsersTokenIsForThem() { - agent := "agent-" + s.utils.uuid() - worker := s.hostsLookupOrder(agent) + // A device names no agent id, so the worker hosts the tool for the config it opens by name. + config := store.AgentConfig{CustomerID: s.customerID(), Name: "orders-" + s.utils.uuid(), Mode: store.AgentModeText, + Models: store.AgentModels{LLM: "tooling/tool-model"}, + ToolGroups: []store.ToolGroup{{Name: "orders", Tools: []string{lookupOrder}}}} + s.Require().NoError(s.store.AgentConfigs.Insert(context.Background(), &config)) + worker := s.hostsLookupOrder(config.Name) device := s.data.createUser() - request := textSession(nil) - request.AgentId, request.Llm = &agent, pointerTo("tooling/tool-model") - opened := device.createSession(request) + opened := device.createSession(CreateSessionRequest{ConfigId: &config.ID}) status, body := s.serverClient.actingFor(device).call(http.MethodPost, "/v1/agents/sessions/"+opened.Id+"/respond", RespondRequest{Text: "where is my order", RequestId: pointerTo("request-" + s.utils.uuid())}) From dc97f48cddd1590e2a254f6a0ff86638d766a2c5 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 18:27:16 +0100 Subject: [PATCH 3/3] fix(api): a device's voice session is not keyed under the id it chose A voice session that names no agent id is keyed under its call id, which is its session id. A device may choose that id, so a device naming another user's id as the session id got the agent's conversation created by, and written as, that user: the same impersonation as naming agent_id. createSession and the socket now give a device's voice session an agent id nobody chose. Text sessions already get a fresh one, and a session carrying on a conversation keeps that conversation's. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/session_create.go | 15 +++++++++ .../api/session_identity_unit_test.go | 31 ++++++++++++++++++ acceleration/internal/api/socketws.go | 1 + acceleration/internal/api/socketws_test.go | 32 +++++++++++++++++++ acceleration/internal/session/manager.go | 4 +++ 5 files changed, 83 insertions(+) diff --git a/acceleration/internal/api/session_create.go b/acceleration/internal/api/session_create.go index 1e9e9cabe7..9b98fa6291 100644 --- a/acceleration/internal/api/session_create.go +++ b/acceleration/internal/api/session_create.go @@ -49,6 +49,7 @@ func (s *Server) createSession(ctx context.Context, request *createSessionReques } spec := specOf(*request.Body, customerID, config) + keyDeviceAgent(ctx, &spec) ctx = s.threadConversation(ctx, customerID, &spec) // Who asked comes from the credential rather than from specOf, which merges the request // with the config and so only ever sees what the caller was willing to say about @@ -156,6 +157,20 @@ var errDeviceMemoryUser = forbidden("memory.user_id is sent server-side unless i var errAnonymousMemory = forbidden("memory needs a signed-in user: an anonymous caller's name is a claim " + "nobody checked, so the memories kept under it could be anyone's") +// keyDeviceAgent gives an end user's device's voice session an agent id nobody chose. +// +// Why: a voice session that names no agent id is keyed under its call id, which is its session +// id, and a device picks that. The agent id is the Chat user the conversation is created by +// and written as, which a device may not choose (errDeviceAgentID). A text session is given a +// fresh one already. One that carries on a conversation is left as it is: opening that +// conversation refuses an agent id other than the one it was kept under. +func keyDeviceAgent(ctx context.Context, spec *session.Spec) { + if ServerSideFrom(ctx) || spec.Text || spec.AgentID != "" || spec.ConversationID != "" { + return + } + spec.AgentID = session.NewAgentID() +} + // errDeviceAgentUser refuses an end user's device naming the user the agent joins and writes as. var errDeviceAgentUser = forbidden("user_id is sent server-side unless it is the default " + session.DefaultUserID + " or the caller's own user id: the agent joins the call and writes " + diff --git a/acceleration/internal/api/session_identity_unit_test.go b/acceleration/internal/api/session_identity_unit_test.go index 8ac91ec1e3..f415f187fb 100644 --- a/acceleration/internal/api/session_identity_unit_test.go +++ b/acceleration/internal/api/session_identity_unit_test.go @@ -76,3 +76,34 @@ func TestABackendNamesAnyAgentIdentity(t *testing.T) { require.False(t, refused) } + +// A device's voice session is keyed under its call id, which is the session id it chose, so it +// is given an agent id nobody chose instead. +func TestADevicesVoiceSessionIsNotKeyedUnderTheIdItChose(t *testing.T) { + for _, kind := range []auth.Kind{auth.KindAuthenticated, auth.KindGuest, auth.KindAnonymous} { + spec := session.Spec{ID: "bob"} + keyDeviceAgent(deviceAsking(kind, "alice"), &spec) + + require.NotEmpty(t, spec.AgentID, string(kind)) + require.NotEqual(t, "bob", spec.AgentID, string(kind)) + } +} + +func TestABackendsVoiceSessionIsStillKeyedUnderItsCall(t *testing.T) { + spec := session.Spec{ID: "bob"} + keyDeviceAgent(backendAsking(), &spec) + + require.Empty(t, spec.AgentID, "Normalize keys it under its call id") +} + +// A text session gets a fresh agent id from Normalize, and a resumed one its conversation's. +func TestADevicesTextOrResumedSessionKeepsItsAgentIDUnset(t *testing.T) { + for name, spec := range map[string]session.Spec{ + "text": {ID: "bob", Text: true}, + "resumed": {ID: "bob", ConversationID: "agent:mine"}, + } { + keyDeviceAgent(deviceAsking(auth.KindAuthenticated, "alice"), &spec) + + require.Empty(t, spec.AgentID, name) + } +} diff --git a/acceleration/internal/api/socketws.go b/acceleration/internal/api/socketws.go index 2113abb524..b16e57d25f 100644 --- a/acceleration/internal/api/socketws.go +++ b/acceleration/internal/api/socketws.go @@ -178,6 +178,7 @@ func (s *Server) openSocketSession(w http.ResponseWriter, r *http.Request) { spec := specOf(start.Session, customerID, config) // A socket session carries audio, so voice is started on it whatever the frame says. spec.Text = false + keyDeviceAgent(ctx, &spec) ctx = s.threadConversation(ctx, customerID, &spec) spec.Caller = CallerFrom(ctx) spec.CallerKind = KindFrom(ctx) diff --git a/acceleration/internal/api/socketws_test.go b/acceleration/internal/api/socketws_test.go index 9949ebaf18..4b9c740482 100644 --- a/acceleration/internal/api/socketws_test.go +++ b/acceleration/internal/api/socketws_test.go @@ -216,6 +216,38 @@ func (s *SocketSessionSuite) TestADeviceMayNotHandTheSocketAnotherAgentIdentity( } } +// A voice session is keyed under its call id, which is the session id a device may choose, so +// a device's voice session, on the socket or by createSession, is given an agent id nobody +// chose, while a backend's keeps its id. +func (s *SocketSessionSuite) TestADevicesVoiceSessionIsNotKeyedUnderTheIdItChose() { + for _, device := range []*testClient{s.client, s.guestClient, s.anonymousClient} { + chosen := "someone-" + s.utils.uuid() + + answered := s.socketStartedWith(device, map[string]any{"id": chosen}) + + s.Equal(chosen, answered["id"], string(device.kind)) + s.NotEqual(chosen, answered["agent_id"], string(device.kind)) + s.NotEmpty(answered["agent_id"], string(device.kind)) + + called := "someone-" + s.utils.uuid() + created := device.createSession(CreateSessionRequest{Id: &called, StartVoice: pointerTo(true)}) + s.NotEqual(called, created.AgentId, "createSession, %s", device.kind) + s.NotEmpty(created.AgentId, "createSession, %s", device.kind) + } + chosen := "backend-" + s.utils.uuid() + s.Equal(chosen, s.socketStartedWith(s.serverClient, map[string]any{"id": chosen})["agent_id"]) +} + +// socketStartedWith starts a socket session asked for as asked and returns the session it was +// answered with. +func (s *SocketSessionSuite) socketStartedWith(client *testClient, asked map[string]any) map[string]any { + connection := client.opens("/v1/agents/socket") + s.Require().NoError(connection.WriteJSON(map[string]any{"type": "start", "sample_rate": 24_000, "session": asked})) + answered := s.readFrame(connection) + s.Require().Equal("session", answered["type"], "the socket answered %v", answered) + return answered["session"].(map[string]any) +} + // assertSocketRefuses checks a device's start frame is refused as its create was, and that // both say the field's own refusal rather than another field's. func (s *SocketSessionSuite) assertSocketRefuses(device *testClient, sent map[string]any, refusal APIError) { diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index 1d68c9b29f..444ef4de46 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -2566,6 +2566,10 @@ func memoryFailed(ctx context.Context, err error) error { // newID is a handle for an agent or a turn. It is random rather than sequential because it // is the only thing standing between two customers who both guessed at an id. +// NewAgentID is a fresh agent id, which nobody chose, for a session that must not be keyed under +// an id its caller picked. +func NewAgentID() string { return newID() } + func newID() string { raw := make([]byte, 16) // rand.Read on crypto/rand never returns an error, which is why the result is not