From 568baf885a8f90946f8e6210883652e6aa86f30b Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:02:15 +0100 Subject: [PATCH 1/8] [AI-3412] Python: refuse a userId on a device's connections calls --- plugins/stream/tests/test_connections.py | 60 +++++++++++++++++++ .../plugins/stream/connections.py | 6 ++ 2 files changed, 66 insertions(+) diff --git a/plugins/stream/tests/test_connections.py b/plugins/stream/tests/test_connections.py index e8fc52fa78..bd1430515d 100644 --- a/plugins/stream/tests/test_connections.py +++ b/plugins/stream/tests/test_connections.py @@ -189,6 +189,14 @@ async def router() -> AsyncIterator[ConnectionsRouter]: await server.close() +@pytest.fixture +def device(router: ConnectionsRouter) -> stream.Client: + """A device: the app's key and its user's token, no secret.""" + return stream.Client( + url=router.url, api_key="key", token="jean-token", authenticate=False + ) + + @pytest.fixture def api(router: ConnectionsRouter) -> stream.Client: """A backend holding the app's key and secret, which the router reads the user from.""" @@ -464,3 +472,55 @@ async def test_a_refusal_is_the_routers_error( assert refused.value.status == 404 assert refused.value.code == "connection_not_found" assert "reading the connection missing" in str(refused.value) + + @pytest.mark.parametrize("call", ["create", "authorize", "get", "list", "delete"]) + async def test_a_device_naming_a_user_is_refused_before_the_router( + self, device: stream.Client, router: ConnectionsRouter, call: str + ): + methods = { + "create": lambda: device.connections.create("linear", user_id="alice"), + "authorize": lambda: device.connections.authorize("c-1", user_id="alice"), + "get": lambda: device.connections.get("c-1", user_id="alice"), + "list": lambda: device.connections.list(user_id="alice"), + "delete": lambda: device.connections.delete("c-1", user_id="alice"), + } + + with pytest.raises(ValueError, match="acts only as that user"): + await methods[call]() + + assert router.requests == [] + + async def test_a_device_naming_no_user_sends_what_it_always_did( + self, device: stream.Client, router: ConnectionsRouter + ): + apps = router.add("github") + + for user in (None, ""): + await device.connections.get(apps["id"], user_id=user) + await device.connections.list(user_id=user) + + for sent in router.requests: + assert sent["headers"]["Authorization"] == "Bearer jean-token" + assert sent["headers"]["Stream-Auth-Type"] == "jwt" + assert USER not in sent["headers"] + assert [r["query"] for r in router.requests][1] == { + "owner_type": "app", + "limit": "200", + } + + async def test_a_customer_id_client_still_names_a_user( + self, router: ConnectionsRouter + ): + # A router that trusts the customer id reads the user from the header; the client + # holds a token and no API key, and that call is not a device's. + page = stream.Client(url=router.url, customer_id="acme").as_user( + "jean", "jean-token" + ) + + await page.connections.create("linear", user_id="alice") + + sent = router.sent("POST", CONNECTIONS) + assert sent["body"]["owner"] == {"type": "user", "user_id": "alice"} + assert sent["headers"][USER] == "alice" + assert sent["headers"]["X-Customer-Id"] == "acme" + assert "Authorization" not in sent["headers"] diff --git a/plugins/stream/vision_agents/plugins/stream/connections.py b/plugins/stream/vision_agents/plugins/stream/connections.py index c909406f18..ac22b19da5 100644 --- a/plugins/stream/vision_agents/plugins/stream/connections.py +++ b/plugins/stream/vision_agents/plugins/stream/connections.py @@ -166,6 +166,12 @@ def _client(self, user_id: Optional[str]) -> AuthenticatedClient: """The generated client acting for ``user_id``, replacing whoever this client acts for. Without one it acts for nobody extra: the user the client was built for stays.""" if user_id: + if not self._backend.server_side: + raise ValueError( + "a user's connections keep the app's credential, which only a backend " + "holds; a device holds its user's token (as_user) and acts only as " + "that user, so leave user_id off" + ) return acting_for(self._backend, user_id).client() return replace(self._backend, acting_for="").client() From 2c2862198444c456311605c6a723abdce309e357 Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:03:24 +0100 Subject: [PATCH 2/8] [AI-3412] Go: refuse a userId on a device's connections calls --- sdks/go/client/connections.go | 9 ++- sdks/go/client/connections_test.go | 111 +++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+), 1 deletion(-) diff --git a/sdks/go/client/connections.go b/sdks/go/client/connections.go index 8377cd6e53..db21a681f3 100644 --- a/sdks/go/client/connections.go +++ b/sdks/go/client/connections.go @@ -13,7 +13,8 @@ import ( const connectionsPage = 200 // Connections are the accounts the app and its users hold at connectors, such as a user's -// Linear: what an agent's tools reach that account through. Only a backend may ask. +// Linear: what an agent's tools reach that account through. Only a backend may ask, and a device +// holding a user's token (SetUser) is refused when it names a user. // // Every method takes the user as a parameter, named once per call. The user goes to the router // as the owner and as X-Stream-User-Id alike, so the two never differ. A user-owned connection @@ -186,6 +187,12 @@ func (c *Connections) reach(id, userID string) (*acceleration.ClientWithResponse // client acts for otherwise. func (c *Connections) api(userID string) (*acceleration.ClientWithResponses, error) { backend := c.client.backend + // A device holds its user's token, which the router answers with 403 on any connection call. + // The customer id path sends no token and is left as it was. + if userID != "" && backend.Authenticate && backend.UserID != "" { + return nil, errors.New("client: a user's connections keep the app's credential, which only a backend " + + "holds; a device holds its user's token (SetUser) and acts only as that user, so leave the user off") + } backend.ActingFor = userID //nolint:staticcheck // SA1019: a call names its user here, replacing the one the client acts for return backend.Client() } diff --git a/sdks/go/client/connections_test.go b/sdks/go/client/connections_test.go index 0f83e129b8..64f6eabd3d 100644 --- a/sdks/go/client/connections_test.go +++ b/sdks/go/client/connections_test.go @@ -508,3 +508,114 @@ func TestEveryCallSendsTheUserItNamesAsTheActingUser(t *testing.T) { t.Errorf("the lists acted for %q", acting) } } + +// connectionCalls is every connections call naming a user, as a device or a page would make it. +func connectionCalls(connections *Connections) map[string]func() error { + call := func(_ any, err error) error { return err } + return map[string]func() error{ + "create": func() error { + return call(connections.Create(context.Background(), ConnectionRequest{Connector: "linear", UserID: "alice"})) + }, + "authorize": func() error { + return call(connections.Authorize(context.Background(), "c-1", AuthorizeOptions{UserID: "alice"})) + }, + "get": func() error { + return call(connections.Get(context.Background(), "c-1", ConnectionOptions{UserID: "alice"})) + }, + "list": func() error { + return call(connections.List(context.Background(), ConnectionFilter{UserID: "alice"})) + }, + "delete": func() error { + return connections.Delete(context.Background(), "c-1", ConnectionOptions{UserID: "alice"}) + }, + } +} + +// Catches a device that names a user on a connections call and gets a late 403 from the router +// instead of an error here, before anything is sent. +func TestADeviceNamingAUserIsRefusedBeforeTheRouter(t *testing.T) { + backend := newRouter(t) + app, err := New(stream.Backend{URL: backend.URL, APIKey: "key", APISecret: "secret"}) + if err != nil { + t.Fatal(err) + } + device, err := app.SetUser("jean", "jean-token") + if err != nil { + t.Fatal(err) + } + + for name, call := range connectionCalls(device.Connections()) { + err := call() + if err == nil || !strings.Contains(err.Error(), "acts only as that user") { + t.Errorf("%s answered %v", name, err) + } + } + + backend.mu.Lock() + defer backend.mu.Unlock() + if len(backend.asked) != 0 { + t.Errorf("the router was sent %v", backend.asked) + } +} + +// Catches a refusal that also hits a device naming no user, or an empty one, or a backend: +// these were sent before and still are, with the device's token and no acting user. +func TestADeviceNamingNoUserAndABackendSendWhatTheyAlwaysDid(t *testing.T) { + backend := newRouter(t) + app, err := New(stream.Backend{URL: backend.URL, APIKey: "key", APISecret: "secret"}) + if err != nil { + t.Fatal(err) + } + device, err := app.SetUser("jean", "jean-token") + if err != nil { + t.Fatal(err) + } + created := connectFor(t, app.Connections(), "github", "") + + if _, err := device.Connections().Get(t.Context(), *created.Id, ConnectionOptions{UserID: ""}); err != nil { + t.Fatal(err) + } + if _, err := device.Connections().List(t.Context(), ConnectionFilter{}); err != nil { + t.Fatal(err) + } + connectFor(t, app.Connections(), "linear", "alice") + if acting := backend.actingFor("POST", "/v1/agents/connections"); !slices.Equal(acting, []string{"", "alice"}) { + t.Errorf("a backend's creates acted for %q", acting) + } + + backend.mu.Lock() + defer backend.mu.Unlock() + // The two device requests are the second and third the router heard. + for _, heard := range backend.heard[1:3] { + if heard.Get(stream.AuthorizationHeader) != "jean-token" || heard.Get(stream.AuthTypeHeader) != stream.AuthTypeJWT { + t.Errorf("the device sent %v", heard) + } + if heard.Get(stream.UserHeader) != "" { + t.Errorf("the device named a user: %v", heard) + } + } +} + +// Catches the refusal reaching the customer id path, where SetUser holds a token the client does +// not send and the router reads the user from X-Stream-User-Id: that call works today. +func TestACustomerIDClientStillNamesAUser(t *testing.T) { + backend := newRouter(t) + page, err := backend.client(t).SetUser("jean", "jean-token") + if err != nil { + t.Fatal(err) + } + + created := connectFor(t, page.Connections(), "linear", "alice") + + if *created.Owner.UserId != "alice" { + t.Errorf("the connection came back as %+v", created) + } + if acting := backend.actingFor("POST", "/v1/agents/connections"); !slices.Equal(acting, []string{"alice"}) { + t.Errorf("the create acted for %q", acting) + } + backend.mu.Lock() + defer backend.mu.Unlock() + if heard := backend.heard[0]; heard.Get(stream.CustomerHeader) != "acme" || heard.Get(stream.AuthorizationHeader) != "" { + t.Errorf("the customer id client sent %v", heard) + } +} From feed5d28551a4c6a7ddab8e156b42473f8a48533 Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:04:20 +0100 Subject: [PATCH 3/8] [AI-3412] Ruby: refuse a user_id on a device's connections calls --- .../getstream/vision_agents/connections.rb | 31 ++++++++--- sdks/ruby/test/connections_test.rb | 52 +++++++++++++++++++ 2 files changed, 75 insertions(+), 8 deletions(-) diff --git a/sdks/ruby/lib/getstream/vision_agents/connections.rb b/sdks/ruby/lib/getstream/vision_agents/connections.rb index de8102a9cc..b2a3b233e4 100644 --- a/sdks/ruby/lib/getstream/vision_agents/connections.rb +++ b/sdks/ruby/lib/getstream/vision_agents/connections.rb @@ -4,7 +4,7 @@ module GetStream module VisionAgents # The accounts the app and its users hold at connectors, such as a user's Linear: what an # agent's tools reach that account through. Server side only: the router refuses a user's - # token. + # token, and a client holding one is refused naming a user before anything is sent. # # Every method takes the user as user_id:, named once per call. It goes to the router as # the owner and in X-Stream-User-Id alike, so the two never differ, whoever the client acts @@ -32,9 +32,10 @@ def initialize(client) # @param label [String] tells the owner's connections to the same connector apart. # @return [Hash] the Connection, pending until an account is connected. def create(connector, label: nil, user_id: nil) - owner = user_id.to_s.empty? ? { type: "app" } : { type: "user", user_id: user_id } + user = named(user_id) + owner = user.empty? ? { type: "app" } : { type: "user", user_id: user } @client.post(CONNECTIONS, body: { connector_id: connector, label: presence(label), owner: owner }, - user_id: user_id.to_s) + user_id: user) end # Starts the provider's consent for a connection: a first one for a pending connection, @@ -47,14 +48,14 @@ def create(connector, label: nil, user_id: nil) # @return [Hash] the Authorization: launch_url, handoff_token and expires_at. def authorize(id, return_url: nil, user_id: nil) @client.post("#{CONNECTION}/authorizations", path: { id: id }, body: { return_url: presence(return_url) }, - user_id: user_id.to_s) + user_id: named(user_id)) end # One connection, the user's or the app's. # # @return [Hash] the Connection. def get(id, user_id: nil) - @client.get(CONNECTION, path: { id: id }, user_id: user_id.to_s) + @client.get(CONNECTION, path: { id: id }, user_id: named(user_id)) end # Every connection of the user's, or of the app's without one, newest first, read page by @@ -63,10 +64,11 @@ def get(id, user_id: nil) # @param connector [String] keeps one connector's. nil is every connector's. # @return [Array] the Connections. def list(connector: nil, user_id: nil) - query = { owner_type: user_id.to_s.empty? ? "app" : "user", connector_id: presence(connector), limit: PAGE } + user = named(user_id) + query = { owner_type: user.empty? ? "app" : "user", connector_id: presence(connector), limit: PAGE } items = [] loop do - page = @client.get(CONNECTIONS, query: query, user_id: user_id.to_s) + page = @client.get(CONNECTIONS, query: query, user_id: user) items.concat(page["items"] || []) query[:cursor] = page["next_cursor"] return items unless page["has_more"] && !query[:cursor].to_s.empty? @@ -76,11 +78,24 @@ def list(connector: nil, user_id: nil) # Disconnects a connection, the user's or the app's, and drops its credentials. One an # agent config binds as its fixed connection is refused with a 409. def delete(id, user_id: nil) - @client.delete(CONNECTION, path: { id: id }, user_id: user_id.to_s) + @client.delete(CONNECTION, path: { id: id }, user_id: named(user_id)) end private + # The user a call names, or ConfigurationError for a device naming one: it holds its own + # user's token, which the router refuses here, so the call is refused before it is sent. + def named(user_id) + user = user_id.to_s + if !user.empty? && !@client.server_side? + raise ConfigurationError, + "a user's connections keep the app's credential, which only a backend holds; a device " \ + "holds its user's token (as_user) and acts only as that user, so leave user_id off" + end + + user + end + def presence(value) value.to_s.empty? ? nil : value end diff --git a/sdks/ruby/test/connections_test.rb b/sdks/ruby/test/connections_test.rb index 3b59c02b12..f61df19808 100644 --- a/sdks/ruby/test/connections_test.rb +++ b/sdks/ruby/test/connections_test.rb @@ -173,4 +173,56 @@ def test_another_user_s_connection_is_the_router_s_not_found assert_equal 404, error.status assert_equal "getConnection", error.operation end + + # Api key and its user's token, no secret. + def device + VA::Client.new(url: @router.url, api_key: "key", token: "jean-token", authenticate: false) + end + + def test_a_device_naming_a_user_is_refused_before_sending + calls = { + create: -> { device.connections.create("linear", user_id: "alice") }, + authorize: -> { device.connections.authorize("conn_1", user_id: "alice") }, + get: -> { device.connections.get("conn_1", user_id: "alice") }, + list: -> { device.connections.list(user_id: "alice") }, + delete: -> { device.connections.delete("conn_1", user_id: "alice") } + } + + calls.each do |name, call| + error = assert_raises(VA::ConfigurationError, name.to_s, &call) + assert_match(/acts only as that user/, error.message) + end + %i[get post delete].each { |method| assert_empty @router.seen(method, %r{\A/v1/agents/connections}) } + end + + def test_a_device_naming_no_user_sends_what_it_always_did + @router.on(:get, "#{CONNECTIONS}/conn_1", body: { "id" => "conn_1" }) + @router.on(:get, CONNECTIONS, body: { "items" => [], "has_more" => false }) + + [nil, ""].each do |user| + device.connections.get("conn_1", user_id: user) + device.connections.list(user_id: user) + end + + sent = @router.seen(:get, %r{\A/v1/agents/connections}) + assert_equal 4, sent.size + sent.each do |request| + assert_equal "Bearer jean-token", request.headers["authorization"] + assert_equal "jwt", request.headers["stream-auth-type"] + refute request.headers.key?("x-stream-user-id") + end + end + + def test_a_customer_id_client_still_names_a_user + @router.on(:post, CONNECTIONS, status: 201, body: { "id" => "conn_1" }) + page = VA::Client.new(url: @router.url, customer_id: CUSTOMER).as_user("jean", "jean-token") + + page.connections.create("linear", user_id: "alice") + + request = @router.last(:post, CONNECTIONS) + assert_equal({ "type" => "user", "user_id" => "alice" }, request.json["owner"]) + assert_equal "alice", request.headers["x-stream-user-id"] + assert_equal CUSTOMER, request.headers["x-customer-id"] + refute request.headers.key?("authorization") + end end From 3a5b04d6f30d1694392ca32e8fc46cfa31870ffc Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:05:58 +0100 Subject: [PATCH 4/8] [AI-3412] Rust: refuse a user_id on a device's connections calls --- sdks/rust/src/connections.rs | 23 ++++++--- sdks/rust/tests/connections.rs | 94 ++++++++++++++++++++++++++++++++++ 2 files changed, 109 insertions(+), 8 deletions(-) diff --git a/sdks/rust/src/connections.rs b/sdks/rust/src/connections.rs index f62717fe39..cff0418a40 100644 --- a/sdks/rust/src/connections.rs +++ b/sdks/rust/src/connections.rs @@ -36,7 +36,8 @@ pub struct ConnectionFilter { } /// The accounts the app and its users hold at connectors, such as a user's Linear: what an -/// agent's tools reach that account through. Server side only. +/// agent's tools reach that account through. Server side only: a client holding a user's token +/// is refused naming a user, before anything is sent. /// /// Every call names its user once, as `user_id`. A user goes to the router as the owner and as /// `X-Stream-User-Id` alike, so the two never differ. A user's connection is reached only @@ -90,7 +91,7 @@ impl Connections { user_id: None, }, }; - self.acting(user_id) + self.acting(user_id)? .create_connection(&types::ConnectionRequest { auth_scheme: None, connector_id: new.connector.clone(), @@ -131,7 +132,7 @@ impl Connections { /// A user's list holds only that user's connections, not the app's. pub async fn list(&self, filter: &ConnectionFilter) -> Result> { let user_id = named(filter.user_id.as_deref()); - let client = self.acting(user_id); + let client = self.acting(user_id)?; let mut query = ListConnectionsQuery { owner_type: Some(if user_id.is_some() { "user" } else { "app" }.into()), connector_id: filter.connector.clone(), @@ -163,15 +164,21 @@ impl Connections { if id.is_empty() { return Err(Error::configuration("a connection needs its id")); } - Ok(self.acting(named(user_id))) + self.acting(named(user_id)) } /// This client acting for `user_id`; with none, as it was built, acting for whoever - /// `ClientOptions::user_id` names, if anyone. - fn acting(&self, user_id: Option<&str>) -> Client { + /// `ClientOptions::user_id` names, if anyone. A device holds its own user's token, which the + /// router refuses here, so naming a user from one is refused before anything is sent. + fn acting(&self, user_id: Option<&str>) -> Result { match user_id { - Some(user_id) => self.client.acting_for(user_id), - None => self.client.clone(), + Some(_) if !self.client.server_side() => Err(Error::configuration( + "a user's connections keep the app's credential, which only a backend holds; a \ + device holds its user's token (as_user) and acts only as that user, so leave \ + user_id off", + )), + Some(user_id) => Ok(self.client.acting_for(user_id)), + None => Ok(self.client.clone()), } } } diff --git a/sdks/rust/tests/connections.rs b/sdks/rust/tests/connections.rs index 6287cdcda9..5ec1135fdb 100644 --- a/sdks/rust/tests/connections.rs +++ b/sdks/rust/tests/connections.rs @@ -459,3 +459,97 @@ async fn another_users_connection_is_the_routers_not_found() { }; assert_eq!(failure.code, "connection_not_found"); } + +/// An API key and its user's token, no secret: what a device holds. +fn device(server: &Server) -> Client { + Client::new(ClientOptions { + url: Some(server.url.clone()), + api_key: Some("key".into()), + token: Some("jean-token".into()), + user_id: Some("jean".into()), + authenticate: Some(false), + ..Default::default() + }) + .unwrap() +} + +#[tokio::test] +async fn a_device_naming_a_user_is_refused_before_the_router() { + let server = Server::start().await; + let connections = device(&server).connections(); + + let refused = [ + connections.create(&new(Some("ada"))).await.map(drop), + connections + .authorize("conn_1", &authorization(Some("ada"))) + .await + .map(drop), + connections.get("conn_1", Some("ada")).await.map(drop), + connections.list(&filter(Some("ada"))).await.map(drop), + connections.delete("conn_1", Some("ada")).await, + ]; + + for refused in refused { + match refused { + Err(Error::Configuration(message)) => { + assert!(message.contains("acts only as that user"), "{message}") + } + other => panic!("not refused as a configuration error: {other:?}"), + } + } + assert!(server.seen().is_empty()); +} + +#[tokio::test] +async fn a_device_naming_no_user_sends_what_it_always_did() { + let server = Server::start().await; + server.route( + Method::GET, + "/v1/agents/connections/conn_1", + 200, + connection("conn_1", "github", None), + ); + server.route( + Method::GET, + "/v1/agents/connections", + 200, + connections(vec![], None), + ); + let connections = device(&server).connections(); + + for user in [None, Some("")] { + connections.get("conn_1", user).await.unwrap(); + connections.list(&filter(user)).await.unwrap(); + } + + let seen = server.seen(); + assert_eq!(seen.len(), 4); + for seen in seen { + assert_eq!(seen.header("authorization"), "Bearer jean-token"); + assert_eq!(seen.header("stream-auth-type"), "jwt"); + assert!(acting_users(&seen).is_empty()); + } +} + +#[tokio::test] +async fn a_customer_id_client_still_names_a_user() { + let server = Server::start().await; + server.route( + Method::POST, + "/v1/agents/connections", + 201, + users("conn_1", "linear", "ada"), + ); + let page = server.client().as_user("jean", "jean-token").unwrap(); + + page.connections().create(&new(Some("ada"))).await.unwrap(); + + let seen = server.request(Method::POST, "/v1/agents/connections"); + assert_eq!( + seen.body["owner"], + json!({"type": "user", "user_id": "ada"}) + ); + assert_eq!(acting_users(&seen), ["ada"]); + assert_eq!(seen.header("x-customer-id"), "examples"); + assert_eq!(seen.header("authorization"), ""); +} From 235763e20d61fe0f57a1d25b6b92dfa0df94650e Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:06:10 +0100 Subject: [PATCH 5/8] [AI-3412] Changelog and SDK skill note: a device naming a user on a connections call --- .claude/skills/sdk/SKILL.md | 1 + CHANGELOG.md | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 3ac4a7df6b..e9d5b8f44c 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -943,3 +943,4 @@ Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Con Ruby connections and the user parameter (AI-3380, AI-3387): `Client#connections` has `create(connector, label:, user_id:)`, `authorize(id, return_url:, user_id:)`, `get(id, user_id:)`, `list(connector:, user_id:)` (every page, `owner_type` app or user) and `delete(id, user_id:)`; a `user_id` is the owner on create and `X-Stream-User-Id` on every call, none is the app's connection with no header. `Client#get`, `post`, `put`, `patch`, `delete` and `socket` take an optional `user_id:` last (nil keeps whoever the backend acts for, empty drops it), and `Backend#acting_for` keeps working with a `@deprecated` tag pointing at it; `Dispatch#answer` acts through `Backend#acting` (`@api private`). Other SDKs follow the same rule (AI-3378..AI-3383). A screened turn carries its guardrail check: `TimelineEntry.guardrail` and the `guardrail` field of the session socket's `turn` frame, a `GuardrailCheck` (`kind`, `model`, `probability`, `threshold`, `allowed`, `latency_ms`, `held_ms`, `mode`, `failed`), absent when no check ran; a written aside (`Agent.Ask`) is no turn, so its check is not recorded. A `type: decision_model` guardrail.md takes a `question:` key, and a guardrail webhook's body has `conversation`, the lines said before the turn. Go has the regenerated client and `agents.GuardrailAsk.Conversation`. The generated clients are regenerated for Go, JavaScript types and Python `plugins/stream`. Other SDKs need to update: Ruby, PHP, .NET and Rust should regenerate for `GuardrailCheck`, and add `conversation` to their guardrail webhook body where they have one; Swift, Kotlin and Dart read `guardrail` off the `turn` frame once they show one (Swift's client was not regenerated here: its generator needs the chat repo's `tools/openapi`). Acting for a user (AI-3396): Go deprecated `Backend.ActingFor`: name the user on the call where it takes one (`UserID` of `client.Connections()` options, `XStreamUserId` of a generated call's params such as `CreateScheduledTaskParams`, or an `X-Stream-User-Id` set on one request with an `acceleration.RequestEditorFn`); `client.Agent(...)` calls take no per-call user yet, so `ActingFor` stays how they act for one. `ActingFor` keeps working and sends what it always did. Other SDKs need to update: JavaScript (#2110), Python (#2103), Ruby (#2102) and PHP (#2101) deprecate their own helper in their open PRs, each with an optional per-call user; .NET (#2099) and Rust (#2100) add the per-call user and have no public helper to deprecate. Until those merge, none of them is deprecated. +A device naming a user on a connections call (AI-3412): the router answers every connections call from a user token with 403 `server_side_only` (the operations carry no `x-client-accessible`, so `refuseClientSide` stops it before the handler, `acceleration/internal/api/server.go:1262`), so a device with a `userId` is refused before sending. JavaScript (`sdks/js/src/connections.ts:137`) and PHP (`Backend::speakingFor`) already did; Python (`connections.py`, `Connections._client`), Go (`client/connections.go`, `Connections.api`), Ruby (`connections.rb`, `named`) and Rust (`connections.rs`, `acting`) now do. A device is a client with a user token: Python, Ruby and Rust key it on the SDK's own `server_side`, Go on `Authenticate` with a `UserID` (a Go client with a `Token` and no `UserID` counts as server side, as `ServerSide()` does). A client on a router that trusts the customer id (`as_user`/`SetUser` with `customer_id` and no API key) is not refused in those four: it sends no token and works against a dev router today; JavaScript still refuses it (its `serverSide` is false there). Other SDKs need to update: .NET follows in the AI-3410 PR (`Connections.SendAsync`, `Connections.cs:152`). diff --git a/CHANGELOG.md b/CHANGELOG.md index 9bac998668..fc9e9b3f0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Features +### The Python, Go, Ruby and Rust SDKs refuse a user on a device's connections call + +A client that holds a user's token (`as_user`, `SetUser`) and names `user_id` on a connections call now fails at once with the SDK's configuration error, the way the JavaScript and PHP SDKs do, instead of sending the call for the router's 403. A device acts only as its own user: name the user from a backend that holds the API secret. A call naming no user, and a client on a router that trusts the customer id, work as before. + ### The Rust SDK connects a user's own accounts `Client::connections()` creates, authorizes, reads, lists and deletes connections: `create(&NewConnection { connector, label, user_id })`, `authorize(id, &AuthorizeOptions { return_url, user_id })` (the consent's launch URL, handoff token and expiry), `get(id, user_id)`, `list(&ConnectionFilter { connector, user_id })` (every page) and `delete(id, user_id)`. A user given goes out as both the owner and `X-Stream-User-Id`; `None` is the app's own connection and leaves the client's own `ClientOptions::user_id` as it is. From a7e82f8adfb2f71a73c0836ec23108c3fbcf947b Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:06:27 +0100 Subject: [PATCH 6/8] [AI-3412] SKILL note: why JavaScript refuses a page --- .claude/skills/sdk/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index e9d5b8f44c..4e555620a7 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -943,4 +943,4 @@ Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Con Ruby connections and the user parameter (AI-3380, AI-3387): `Client#connections` has `create(connector, label:, user_id:)`, `authorize(id, return_url:, user_id:)`, `get(id, user_id:)`, `list(connector:, user_id:)` (every page, `owner_type` app or user) and `delete(id, user_id:)`; a `user_id` is the owner on create and `X-Stream-User-Id` on every call, none is the app's connection with no header. `Client#get`, `post`, `put`, `patch`, `delete` and `socket` take an optional `user_id:` last (nil keeps whoever the backend acts for, empty drops it), and `Backend#acting_for` keeps working with a `@deprecated` tag pointing at it; `Dispatch#answer` acts through `Backend#acting` (`@api private`). Other SDKs follow the same rule (AI-3378..AI-3383). A screened turn carries its guardrail check: `TimelineEntry.guardrail` and the `guardrail` field of the session socket's `turn` frame, a `GuardrailCheck` (`kind`, `model`, `probability`, `threshold`, `allowed`, `latency_ms`, `held_ms`, `mode`, `failed`), absent when no check ran; a written aside (`Agent.Ask`) is no turn, so its check is not recorded. A `type: decision_model` guardrail.md takes a `question:` key, and a guardrail webhook's body has `conversation`, the lines said before the turn. Go has the regenerated client and `agents.GuardrailAsk.Conversation`. The generated clients are regenerated for Go, JavaScript types and Python `plugins/stream`. Other SDKs need to update: Ruby, PHP, .NET and Rust should regenerate for `GuardrailCheck`, and add `conversation` to their guardrail webhook body where they have one; Swift, Kotlin and Dart read `guardrail` off the `turn` frame once they show one (Swift's client was not regenerated here: its generator needs the chat repo's `tools/openapi`). Acting for a user (AI-3396): Go deprecated `Backend.ActingFor`: name the user on the call where it takes one (`UserID` of `client.Connections()` options, `XStreamUserId` of a generated call's params such as `CreateScheduledTaskParams`, or an `X-Stream-User-Id` set on one request with an `acceleration.RequestEditorFn`); `client.Agent(...)` calls take no per-call user yet, so `ActingFor` stays how they act for one. `ActingFor` keeps working and sends what it always did. Other SDKs need to update: JavaScript (#2110), Python (#2103), Ruby (#2102) and PHP (#2101) deprecate their own helper in their open PRs, each with an optional per-call user; .NET (#2099) and Rust (#2100) add the per-call user and have no public helper to deprecate. Until those merge, none of them is deprecated. -A device naming a user on a connections call (AI-3412): the router answers every connections call from a user token with 403 `server_side_only` (the operations carry no `x-client-accessible`, so `refuseClientSide` stops it before the handler, `acceleration/internal/api/server.go:1262`), so a device with a `userId` is refused before sending. JavaScript (`sdks/js/src/connections.ts:137`) and PHP (`Backend::speakingFor`) already did; Python (`connections.py`, `Connections._client`), Go (`client/connections.go`, `Connections.api`), Ruby (`connections.rb`, `named`) and Rust (`connections.rs`, `acting`) now do. A device is a client with a user token: Python, Ruby and Rust key it on the SDK's own `server_side`, Go on `Authenticate` with a `UserID` (a Go client with a `Token` and no `UserID` counts as server side, as `ServerSide()` does). A client on a router that trusts the customer id (`as_user`/`SetUser` with `customer_id` and no API key) is not refused in those four: it sends no token and works against a dev router today; JavaScript still refuses it (its `serverSide` is false there). Other SDKs need to update: .NET follows in the AI-3410 PR (`Connections.SendAsync`, `Connections.cs:152`). +A device naming a user on a connections call (AI-3412): the router answers every connections call from a user token with 403 `server_side_only` (the operations carry no `x-client-accessible`, so `refuseClientSide` stops it before the handler, `acceleration/internal/api/server.go:1262`), so a device with a `userId` is refused before sending. JavaScript (`sdks/js/src/connections.ts:137`) and PHP (`Backend::speakingFor`) already did; Python (`connections.py`, `Connections._client`), Go (`client/connections.go`, `Connections.api`), Ruby (`connections.rb`, `named`) and Rust (`connections.rs`, `acting`) now do. A device is a client with a user token: Python, Ruby and Rust key it on the SDK's own `server_side`, Go on `Authenticate` with a `UserID` (a Go client with a `Token` and no `UserID` counts as server side, as `ServerSide()` does). A client on a router that trusts the customer id (`as_user`/`SetUser` with `customer_id` and no API key) is not refused in those four: it sends no token and works against a dev router today; JavaScript still refuses it, because its page says `stream-auth-type=jwt` and the router reads it as the end user (`backend.ts:613`). Other SDKs need to update: .NET follows in the AI-3410 PR (`Connections.SendAsync`, `Connections.cs:152`). From 989bd9235b4efb7eb3c2a12e3a754566ff097840 Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:36:02 +0100 Subject: [PATCH 7/8] AI-3412: Go backend built for a user acts for the user a connections call names A Backend with the API secret and a UserID naming another user on a connections call signed a token for its own user, which the proxy refuses (403). Like the other SDKs, the call now drops the client's own user and sends the app's token with X-Stream-User-Id. Only a client holding a user's Token (SetUser) is refused. Co-Authored-By: Claude Opus 5.5 --- sdks/go/client/connections.go | 11 ++-- sdks/go/client/connections_test.go | 85 ++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 3 deletions(-) diff --git a/sdks/go/client/connections.go b/sdks/go/client/connections.go index db21a681f3..570fda334b 100644 --- a/sdks/go/client/connections.go +++ b/sdks/go/client/connections.go @@ -187,11 +187,16 @@ func (c *Connections) reach(id, userID string) (*acceleration.ClientWithResponse // client acts for otherwise. func (c *Connections) api(userID string) (*acceleration.ClientWithResponses, error) { backend := c.client.backend - // A device holds its user's token, which the router answers with 403 on any connection call. // The customer id path sends no token and is left as it was. if userID != "" && backend.Authenticate && backend.UserID != "" { - return nil, errors.New("client: a user's connections keep the app's credential, which only a backend " + - "holds; a device holds its user's token (SetUser) and acts only as that user, so leave the user off") + // A device holds its user's token, which the router answers with 403 on any connection call. + if backend.Token != "" { + return nil, errors.New("client: a user's connections keep the app's credential, which only a backend " + + "holds; a device holds its user's token (SetUser) and acts only as that user, so leave the user off") + } + // A backend built for one user still holds the secret: this call is the app's, acting for + // the user it names, as in every other SDK. A token signed for its own user would be refused. + backend.UserID = "" } backend.ActingFor = userID //nolint:staticcheck // SA1019: a call names its user here, replacing the one the client acts for return backend.Client() diff --git a/sdks/go/client/connections_test.go b/sdks/go/client/connections_test.go index 64f6eabd3d..82c00a93dd 100644 --- a/sdks/go/client/connections_test.go +++ b/sdks/go/client/connections_test.go @@ -16,6 +16,8 @@ import ( "testing" "time" + "github.com/golang-jwt/jwt/v5" + "github.com/GetStream/Vision-Agents/sdks/go/acceleration" "github.com/GetStream/Vision-Agents/sdks/go/stream" ) @@ -619,3 +621,86 @@ func TestACustomerIDClientStillNamesAUser(t *testing.T) { t.Errorf("the customer id client sent %v", heard) } } + +// claimsHeard are the claims of the token each request the router heard carried, signed with +// secret, without the times they were minted at. +func claimsHeard(t *testing.T, backend *router, secret string) []jwt.MapClaims { + t.Helper() + backend.mu.Lock() + defer backend.mu.Unlock() + var heard []jwt.MapClaims + for _, header := range backend.heard { + claims := jwt.MapClaims{} + if _, err := jwt.ParseWithClaims(header.Get(stream.AuthorizationHeader), claims, + func(*jwt.Token) (any, error) { return []byte(secret), nil }); err != nil { + t.Fatal(err) + } + delete(claims, "iat") + delete(claims, "exp") + heard = append(heard, claims) + } + return heard +} + +// Catches a backend built for one user that names another on a connections call and signs that +// call a token of its own user, which the proxy refuses with 403: it holds the secret, so the call +// is the app's acting for the named user, as Python's acting_for (_backend.py, user_id="") sends. +func TestABackendBuiltForAUserActsForTheUserACallNames(t *testing.T) { + backend := newRouter(t) + app, err := New(stream.Backend{URL: backend.URL, APIKey: "key", APISecret: "secret", UserID: "ada"}) + if err != nil { + t.Fatal(err) + } + connections := app.Connections() + + created := connectFor(t, connections, "linear", "alice") + if _, err := connections.Authorize(t.Context(), *created.Id, AuthorizeOptions{UserID: "alice"}); err != nil { + t.Fatal(err) + } + if _, err := connections.Get(t.Context(), *created.Id, ConnectionOptions{UserID: "alice"}); err != nil { + t.Fatal(err) + } + if listed, err := connections.List(t.Context(), ConnectionFilter{UserID: "alice"}); err != nil || len(listed) != 1 { + t.Fatalf("the list answered %v, %v", listed, err) + } + if err := connections.Delete(t.Context(), *created.Id, ConnectionOptions{UserID: "alice"}); err != nil { + t.Fatal(err) + } + + for at, claims := range claimsHeard(t, backend, "secret") { + if !reflect.DeepEqual(claims, jwt.MapClaims{"server": true}) { + t.Errorf("request %d carried %v", at, claims) + } + } + backend.mu.Lock() + defer backend.mu.Unlock() + if len(backend.heard) != 5 { + t.Fatalf("the router heard %v", backend.asked) + } + for at, heard := range backend.heard { + if heard.Get(stream.UserHeader) != "alice" || heard.Get(stream.AuthTypeHeader) != stream.AuthTypeJWT { + t.Errorf("request %d sent %v", at, heard) + } + } +} + +// Catches the app's token reaching a call that names no user from a backend built for one user: +// that call sent its own user's token and no acting user before, and still does. +func TestABackendBuiltForAUserNamingNoUserSendsWhatItAlwaysDid(t *testing.T) { + backend := newRouter(t) + app, err := New(stream.Backend{URL: backend.URL, APIKey: "key", APISecret: "secret", UserID: "ada"}) + if err != nil { + t.Fatal(err) + } + + if _, err := app.Connections().List(t.Context(), ConnectionFilter{}); err != nil { + t.Fatal(err) + } + + if claims := claimsHeard(t, backend, "secret"); !reflect.DeepEqual(claims, []jwt.MapClaims{{"user_id": "ada"}}) { + t.Errorf("the list carried %v", claims) + } + if acting := backend.actingFor("GET", "/v1/agents/connections"); !slices.Equal(acting, []string{""}) { + t.Errorf("the list acted for %q", acting) + } +} From 71e72b8ef3abc68766a2154727aca6206d8543fb Mon Sep 17 00:00:00 2001 From: Kanat Date: Fri, 20 Nov 2026 16:36:25 +0100 Subject: [PATCH 8/8] AI-3412: say a Go backend built for a user acts for the named user Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk/SKILL.md | 2 +- CHANGELOG.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 4e555620a7..d95e6d85cc 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -943,4 +943,4 @@ Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Con Ruby connections and the user parameter (AI-3380, AI-3387): `Client#connections` has `create(connector, label:, user_id:)`, `authorize(id, return_url:, user_id:)`, `get(id, user_id:)`, `list(connector:, user_id:)` (every page, `owner_type` app or user) and `delete(id, user_id:)`; a `user_id` is the owner on create and `X-Stream-User-Id` on every call, none is the app's connection with no header. `Client#get`, `post`, `put`, `patch`, `delete` and `socket` take an optional `user_id:` last (nil keeps whoever the backend acts for, empty drops it), and `Backend#acting_for` keeps working with a `@deprecated` tag pointing at it; `Dispatch#answer` acts through `Backend#acting` (`@api private`). Other SDKs follow the same rule (AI-3378..AI-3383). A screened turn carries its guardrail check: `TimelineEntry.guardrail` and the `guardrail` field of the session socket's `turn` frame, a `GuardrailCheck` (`kind`, `model`, `probability`, `threshold`, `allowed`, `latency_ms`, `held_ms`, `mode`, `failed`), absent when no check ran; a written aside (`Agent.Ask`) is no turn, so its check is not recorded. A `type: decision_model` guardrail.md takes a `question:` key, and a guardrail webhook's body has `conversation`, the lines said before the turn. Go has the regenerated client and `agents.GuardrailAsk.Conversation`. The generated clients are regenerated for Go, JavaScript types and Python `plugins/stream`. Other SDKs need to update: Ruby, PHP, .NET and Rust should regenerate for `GuardrailCheck`, and add `conversation` to their guardrail webhook body where they have one; Swift, Kotlin and Dart read `guardrail` off the `turn` frame once they show one (Swift's client was not regenerated here: its generator needs the chat repo's `tools/openapi`). Acting for a user (AI-3396): Go deprecated `Backend.ActingFor`: name the user on the call where it takes one (`UserID` of `client.Connections()` options, `XStreamUserId` of a generated call's params such as `CreateScheduledTaskParams`, or an `X-Stream-User-Id` set on one request with an `acceleration.RequestEditorFn`); `client.Agent(...)` calls take no per-call user yet, so `ActingFor` stays how they act for one. `ActingFor` keeps working and sends what it always did. Other SDKs need to update: JavaScript (#2110), Python (#2103), Ruby (#2102) and PHP (#2101) deprecate their own helper in their open PRs, each with an optional per-call user; .NET (#2099) and Rust (#2100) add the per-call user and have no public helper to deprecate. Until those merge, none of them is deprecated. -A device naming a user on a connections call (AI-3412): the router answers every connections call from a user token with 403 `server_side_only` (the operations carry no `x-client-accessible`, so `refuseClientSide` stops it before the handler, `acceleration/internal/api/server.go:1262`), so a device with a `userId` is refused before sending. JavaScript (`sdks/js/src/connections.ts:137`) and PHP (`Backend::speakingFor`) already did; Python (`connections.py`, `Connections._client`), Go (`client/connections.go`, `Connections.api`), Ruby (`connections.rb`, `named`) and Rust (`connections.rs`, `acting`) now do. A device is a client with a user token: Python, Ruby and Rust key it on the SDK's own `server_side`, Go on `Authenticate` with a `UserID` (a Go client with a `Token` and no `UserID` counts as server side, as `ServerSide()` does). A client on a router that trusts the customer id (`as_user`/`SetUser` with `customer_id` and no API key) is not refused in those four: it sends no token and works against a dev router today; JavaScript still refuses it, because its page says `stream-auth-type=jwt` and the router reads it as the end user (`backend.ts:613`). Other SDKs need to update: .NET follows in the AI-3410 PR (`Connections.SendAsync`, `Connections.cs:152`). +A device naming a user on a connections call (AI-3412): the router answers every connections call from a user token with 403 `server_side_only` (the operations carry no `x-client-accessible`, so `refuseClientSide` stops it before the handler, `acceleration/internal/api/server.go:1262`), so a device with a `userId` is refused before sending. JavaScript (`sdks/js/src/connections.ts:137`) and PHP (`Backend::speakingFor`) already did; Python (`connections.py`, `Connections._client`), Go (`client/connections.go`, `Connections.api`), Ruby (`connections.rb`, `named`) and Rust (`connections.rs`, `acting`) now do. A device is a client with a user token: Python, Ruby and Rust key it on the SDK's own `server_side`, Go on `Authenticate` with a `UserID` and a `Token`, since `SetUser` keeps the secret (a Go client with a `Token` and no `UserID` counts as server side, as `ServerSide()` does). A Go `Backend` with the API secret and a `UserID` and no `Token` that names another user drops its own `UserID` for that call and sends the app's token with `X-Stream-User-Id`, as Python's `acting_for` does; before, it signed a token for its own user, which the proxy refused with 403. A client on a router that trusts the customer id (`as_user`/`SetUser` with `customer_id` and no API key) is not refused in those four: it sends no token and works against a dev router today; JavaScript still refuses it, because its page says `stream-auth-type=jwt` and the router reads it as the end user (`backend.ts:613`). Other SDKs need to update: .NET follows in the AI-3410 PR (`Connections.SendAsync`, `Connections.cs:152`). diff --git a/CHANGELOG.md b/CHANGELOG.md index fc9e9b3f0e..00b93e3bee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### The Python, Go, Ruby and Rust SDKs refuse a user on a device's connections call -A client that holds a user's token (`as_user`, `SetUser`) and names `user_id` on a connections call now fails at once with the SDK's configuration error, the way the JavaScript and PHP SDKs do, instead of sending the call for the router's 403. A device acts only as its own user: name the user from a backend that holds the API secret. A call naming no user, and a client on a router that trusts the customer id, work as before. +A client that holds a user's token (`as_user`, `SetUser`) and names `user_id` on a connections call now fails at once with the SDK's configuration error, the way the JavaScript and PHP SDKs do, instead of sending the call for the router's 403. A device acts only as its own user: name the user from a backend that holds the API secret. A call naming no user, and a client on a router that trusts the customer id, work as before. A Go `Backend` with the API secret and a `UserID` that names another user on a connections call now acts for that user with the app's token, as the other SDKs do, instead of signing a token for its own user that the proxy refused. ### The Rust SDK connects a user's own accounts