Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions acceleration/internal/api/chat_channels_hosted_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())})
Expand Down
28 changes: 13 additions & 15 deletions acceleration/internal/api/dispatch_channel_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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()
Expand Down
57 changes: 57 additions & 0 deletions acceleration/internal/api/session_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -156,6 +157,59 @@ 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 " +
"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
}

// errAnonymousConversation refuses conversation_id to a caller whose user id nobody checked.
var errAnonymousConversation = forbidden("conversation_id needs a verified caller: an anonymous caller " +
"carries its conversation on by its session id")
Expand All @@ -167,6 +221,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 {
Expand Down
109 changes: 109 additions & 0 deletions acceleration/internal/api/session_identity_unit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
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)
}

// 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)
}
}
1 change: 1 addition & 0 deletions acceleration/internal/api/socketws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
48 changes: 48 additions & 0 deletions acceleration/internal/api/socketws_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,54 @@ 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)
})
}
}

// 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)
}

// A start frame naming a conversation's channel is refused a caller whose name nobody checked,
// as createSession refuses it.
func (s *SocketSessionSuite) TestAStartFrameFromANameWithoutATokenOpensNoConversation() {
Expand Down
Loading
Loading