diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 594520624..aad43c541 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -943,4 +943,5 @@ 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. +Acting for another user in .NET connections (AI-3410, AI-3412): a `Connections` call that names a user sends the client's server credential and `X-Stream-User-Id`, and drops the user the client was made for (`Backend.Acting` sets `UserId` to empty, `Backend.cs:254`). Behind the proxy that is a `server: true` token, as Python (`_backend.py:463`), JavaScript (`speakingFor`, `backend.ts:575`), PHP (`Backend.php:198`), Ruby (`backend.rb:301`) and Rust (`client.rs:174`) send; **Go differs**: a `Backend` with `UserID` and `ActingFor` signs `{"user_id": }` and adds the header (`stream/backend.go:250-253`, `:273`), a user's token, which Stream's proxy refuses with a 403 when it names another user (`chat/projects/stream-accelerate/proxy.go:430` on master; the 403 is `chat/lib/core/errors/errors.go:223-225`), so a Go client made for a user cannot name another on a connections call; Go should drop `UserID` for the call, as the others do. A client with an API key holding a user's token (a device: `Token` with `UserId`, or `AsUser` of a client with an API key) naming a user on a connections call throws `ConfigurationException` before any request, as JavaScript's `connections.ts:137-146` does; a customer-id client (`ServerSide` true) is unchanged. Other SDKs need to update: Go (the call's user replaces `UserID`), Python, Ruby and Rust (refuse a device's user before sending, AI-3412). 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 00b93e3be..b6cd63e7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ A client that holds a user's token (`as_user`, `SetUser`) and names `user_id` on `VisionAgentsClient.Connections` creates, authorizes, reads, lists and deletes connections: `CreateAsync("linear", new NewConnectionOptions { UserId = "alice" })`, `AuthorizeAsync(id, new AuthorizeOptions { ReturnUrl = ..., UserId = ... })` for the consent's launch URL, handoff token and expiry, `GetAsync(id, userId)`, `ListAsync(new ConnectionFilter { ConnectorId = ..., UserId = ... })` reading every page, and `DeleteAsync(id, userId)`; a user given is sent as the owner and as `X-Stream-User-Id`, and none is the app's own connection (#2099). +A `Connections` call that names a user on a client with an API key holding a user's token throws a `ConfigurationException` before any request, rather than the 403 Stream's proxy answers (#2155). + ### The JavaScript SDK connects a user's own accounts `api.connections` creates, authorizes, reads, lists and deletes connections: `create("linear", { userId })`, `authorize(id, { returnUrl, userId })` for the consent's launch URL, handoff token and expiry, `get(id, { userId })`, `list({ connectorId, userId })` and `delete(id, { userId })`; without `userId` they are the app's own. `Backend.actingFor` is deprecated in favour of the `userId` parameter and works as before (#2110). diff --git a/sdks/dotnet/README.md b/sdks/dotnet/README.md index 012bad57e..b85f1e1a8 100644 --- a/sdks/dotnet/README.md +++ b/sdks/dotnet/README.md @@ -406,6 +406,13 @@ An app's connection is reached by every call of a backend, one naming a user inc `ListAsync` with a `UserId` lists only that user's. Leave the user out for the app's own connection, which any of its agents may be bound to. Connections are server side only. +A user given replaces the one the client was made for (`VisionAgentsOptions.UserId`), and the +request keeps the server credential: behind the proxy it is a server token, not a token for the +client's own user, which is what the router needs to let a backend act for somebody. A client +with an API key holding a user's token is a device. It cannot act for another user, so a call +naming one throws a `ConfigurationException` before any request, and a call naming none is sent +as before. + ## Working on this package Everything runs in Docker; nothing is installed on the host. diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Connections.cs b/sdks/dotnet/src/GetStream.VisionAgents/Connections.cs index 1d0840a24..ec24afcd4 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Connections.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Connections.cs @@ -45,7 +45,9 @@ public sealed record ConnectionFilter /// UserId of the options. A user given is sent as the /// owner and as X-Stream-User-Id alike, so the two never differ. A user's connection is /// reached only by a call naming that user; the app's is reached by every call, one naming a -/// user included. No user is the app's own connection. +/// user included. No user is the app's own connection. A user given replaces the one the client +/// was made for, with the server credential; a client with an API key holding a user's token (a +/// device) refuses a user with a before sending. /// public sealed class Connections { @@ -149,6 +151,11 @@ private static string Path(string id) => string.IsNullOrEmpty(id) /// Sends with this client acting for the user, or as it is when no user is given, whoever it /// acts for otherwise. /// + /// + /// A user given replaces the one the client was made for () + /// and the request keeps the server credential, never a token minted for that one user: the router + /// answers a user token as the device it is, and a device may not name another user. + /// private async Task SendAsync(string? userId, Func> send) { userId = VisionAgentsClient.Blank(userId); @@ -156,6 +163,13 @@ private async Task SendAsync(string? userId, Func seen.Headers[Header])); } + [Fact] + public async Task ABackendMadeForAUserBehindTheProxyNamesAnotherWithAServerTokenAndNoneWithItsOwn() + { + await using var router = await Answering(); + using var ada = new VisionAgentsClient(new VisionAgentsOptions + { + Url = router.Url, + ApiKey = "key", + ApiSecret = Fixtures.Secret, + UserId = "ada", + Authenticate = true, + }); + var cancel = TestContext.Current.CancellationToken; + + await ada.Connections.GetAsync("conn-1", "alice", cancel); + await ada.Connections.GetAsync("conn-1", cancellationToken: cancel); + + var (naming, plain) = (router.Requests[0], router.Requests[1]); + Assert.Equal(("alice", "jwt"), (naming.Headers[Header], naming.Headers["stream-auth-type"])); + var named = Fixtures.Claims(naming.Headers["Authorization"]); + Assert.True(named["server"]!.GetValue()); + Assert.Null(named["user_id"]); + Assert.False(plain.Headers.ContainsKey(Header)); + var own = Fixtures.Claims(plain.Headers["Authorization"]); + Assert.Equal("ada", own["user_id"]!.GetValue()); + Assert.Null(own["server"]); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ADeviceHoldingAUsersTokenRefusesToNameAUserBeforeAnythingIsSent(bool authenticate) + { + await using var router = await Answering(); + using var device = new VisionAgentsClient(new VisionAgentsOptions + { + Url = router.Url, + ApiKey = "key", + Token = "ada-token", + UserId = "ada", + Authenticate = authenticate, + }); + using var derived = new VisionAgentsClient(new VisionAgentsOptions + { + Url = router.Url, + ApiKey = "key", + ApiSecret = Fixtures.Secret, + Authenticate = authenticate, + }).AsUser("ada", "ada-token"); + var cancel = TestContext.Current.CancellationToken; + + foreach (var client in new[] { device, derived }) + { + var connections = client.Connections; + Assert.False(client.ServerSide); + await Assert.ThrowsAsync(() => connections.CreateAsync("linear", new NewConnectionOptions { UserId = "alice" }, cancel)); + await Assert.ThrowsAsync(() => connections.AuthorizeAsync("conn-1", new AuthorizeOptions { UserId = "alice" }, cancel)); + await Assert.ThrowsAsync(() => connections.GetAsync("conn-1", "alice", cancel)); + await Assert.ThrowsAsync(() => connections.ListAsync(new ConnectionFilter { UserId = "alice" }, cancel)); + await Assert.ThrowsAsync(() => connections.DeleteAsync("conn-1", "alice", cancel)); + } + + Assert.Empty(router.Requests); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + public async Task ADeviceWithNoUserOnACallSendsItsOwnTokenAsBefore(string? userId) + { + await using var router = await Answering(); + using var device = new VisionAgentsClient(new VisionAgentsOptions { Url = router.Url, ApiKey = "key", Token = "ada-token", UserId = "ada" }); + var cancel = TestContext.Current.CancellationToken; + + await device.Connections.GetAsync("conn-1", userId, cancel); + await device.Connections.ListAsync(new ConnectionFilter { UserId = userId }, cancel); + + Assert.Equal(2, router.Requests.Count); + Assert.All(router.Requests, seen => + { + Assert.Equal(("Bearer ada-token", "jwt", "key"), (seen.Headers["Authorization"], seen.Headers["Stream-Auth-Type"], seen.Headers["X-Api-Key"])); + Assert.False(seen.Headers.ContainsKey(Header)); + }); + } + + [Fact] + public async Task ACustomerIdClientMadeForAUserStillNamesAnotherOnATrustingRouter() + { + await using var router = await Answering(); + using var ada = Fixtures.Client(router).AsUser("ada", "ada-token"); + var cancel = TestContext.Current.CancellationToken; + + Assert.True(ada.ServerSide); + await ada.Connections.GetAsync("conn-1", "alice", cancel); + + var seen = router.Only("GET", "/v1/agents/connections/conn-1"); + Assert.Equal(("alice", "examples"), (seen.Headers[Header], seen.Headers["X-Customer-Id"])); + Assert.False(seen.Headers.ContainsKey("Authorization")); + } + [Fact] public async Task EmptyOptionalStringsAreLeftOutAndTheOwnerIsTheUserGiven() {