Skip to content
Merged
1 change: 1 addition & 0 deletions .claude/skills/sdk/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 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`).
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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

`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.
Expand Down
60 changes: 60 additions & 0 deletions plugins/stream/tests/test_connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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"]
6 changes: 6 additions & 0 deletions plugins/stream/vision_agents/plugins/stream/connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
14 changes: 13 additions & 1 deletion sdks/go/client/connections.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -186,6 +187,17 @@ 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
// The customer id path sends no token and is left as it was.
if userID != "" && backend.Authenticate && backend.UserID != "" {
// 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()
}
196 changes: 196 additions & 0 deletions sdks/go/client/connections_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -508,3 +510,197 @@ 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)
}
}

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