Skip to content
Draft
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: 12 additions & 0 deletions .claude/skills/sdk/notes/2026-12-01-ed25519-jwt-auth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Ed25519 (EdDSA) JWT authentication

The router's unified JWT auth verifies Ed25519 (`EdDSA`) JWTs across `api_key`, `proxy`, and `noauth` (unverified).

- **HTTP:** `Authorization: Bearer <token>` and public `api_key` as query parameter (`?api_key=...`).
- **WebSocket:**
- Server-side SDKs send `Authorization: Bearer <token>` and `?api_key=...`.
- Browser / client-side SDKs send `Sec-WebSocket-Protocol: bearer, <token>` and `?api_key=...` (the router echoes back `bearer` on 101 so browsers accept the handshake without echoing the JWT).
- **Claims:** `kind` (`server` | `authenticated` | `guest` | `anonymous`), `user_id` (empty for `server`/`anonymous`), `customer_id`, `app_id`, optional `usage_categories` and `team`, required `exp`.
- SDKs omit `customer_id` and `app_id` unless talking directly to a router without a gateway; behind a gateway or in `api_key` mode, the gateway/router resolves them from `api_key`.

Go, JS, Python (`plugins/stream`), Ruby, PHP, Rust, Dart, Swift, and Kotlin are aligned; .NET needs an Ed25519 signing package if `PrivateKey` signing is added there (standard .NET 10 BCL has no Ed25519 implementation).
1 change: 1 addition & 0 deletions plugins/stream/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ dependencies = [
"aiohttp>=3.10",
"httpx>=0.27",
"attrs>=23.2",
"cryptography>=44.0.0",
"pyyaml>=6.0",
]

Expand Down
89 changes: 89 additions & 0 deletions plugins/stream/tests/test_ed25519_backend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import base64
import json
from urllib.parse import parse_qs, urlsplit

import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
Ed25519PrivateKey,
Ed25519PublicKey,
)

from vision_agents.plugins.stream._backend import Backend


@pytest.fixture
def ed25519_pair() -> tuple[Ed25519PublicKey, str]:
private_key = Ed25519PrivateKey.generate()
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
).decode()
return private_key.public_key(), pem


def _verify_bearer(auth_header: str, public_key: Ed25519PublicKey) -> dict[str, object]:
assert auth_header.startswith("Bearer ")
token = auth_header.removeprefix("Bearer ")
raw_header, raw_payload, raw_sig = token.split(".")
header = json.loads(base64.urlsafe_b64decode(raw_header + "=="))
assert header["alg"] == "EdDSA"
sig = base64.urlsafe_b64decode(raw_sig + "==")
public_key.verify(sig, f"{raw_header}.{raw_payload}".encode())
return json.loads(base64.urlsafe_b64decode(raw_payload + "=="))


class TestBackendEd25519:
def test_invalid_private_key_is_refused(self) -> None:
with pytest.raises(ValueError):
Backend(url="http://localhost:8080", private_key="not-a-key")

def test_server_credentials_sign_eddsa_bearer(
self, ed25519_pair: tuple[Ed25519PublicKey, str]
) -> None:
public_key, private_key_pem = ed25519_pair
backend = Backend(
url="http://localhost:8080",
api_key="pub-key",
customer_id="org-1",
app_id="app-1",
private_key=private_key_pem,
team="sales",
usage_categories=["support"],
)

assert backend.server_side is True
headers = backend.headers
assert "X-Api-Key" not in headers
assert "api_key" not in headers

claims = _verify_bearer(headers["Authorization"], public_key)
assert claims["customer_id"] == "org-1"
assert claims["app_id"] == "app-1"
assert claims["kind"] == "server"
assert claims["team"] == "sales"
assert claims["usage_categories"] == ["support"]

def test_client_credentials_and_socket_api_key(
self, ed25519_pair: tuple[Ed25519PublicKey, str]
) -> None:
public_key, private_key_pem = ed25519_pair
backend = Backend(
url="https://router.example.com",
api_key="pub-key",
customer_id="org-1",
app_id="app-1",
user_id="user-42",
private_key=private_key_pem,
)

claims = _verify_bearer(backend.headers["Authorization"], public_key)
assert claims["kind"] == "authenticated"
assert claims["user_id"] == "user-42"

ws = urlsplit(backend.socket("/v1/dispatch?capacity=4"))
assert ws.scheme == "wss"
params = parse_qs(ws.query)
assert params["api_key"] == ["pub-key"]
assert params["capacity"] == ["4"]
95 changes: 87 additions & 8 deletions plugins/stream/vision_agents/plugins/stream/_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
import time
from dataclasses import dataclass, field, replace
from typing import Optional, Sequence, Union
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import load_pem_private_key

from ._errors import raise_refusal
from ._generated import AuthenticatedClient
Expand Down Expand Up @@ -166,8 +170,10 @@ class Backend:

url: Optional[str] = None
customer_id: Optional[str] = None
app_id: str = ""
api_key: Optional[str] = None
api_secret: Optional[str] = None
private_key: str = ""
token: str = ""
user_id: str = ""
authenticate: Optional[bool] = None
Expand Down Expand Up @@ -205,12 +211,19 @@ def __post_init__(self):
# header is missing.
if self.api_key is None:
self.api_key = "" if self.customer_id else os.environ.get(API_KEY_ENV, "")
self.private_key = self.private_key.strip()
if self.private_key:
_load_ed25519_private_key(self.private_key)
# A token that was handed in is the caller's answer to who they are, so an ambient
# secret does not overrule it: without this, a client built the way a device builds
# one turns into a backend as soon as it runs in a process that happens to have the
# secret in its environment, which is most of them and every test.
if self.api_secret is None:
self.api_secret = "" if self.token else os.environ.get(API_SECRET_ENV, "")
self.api_secret = (
""
if (self.token or self.private_key)
else os.environ.get(API_SECRET_ENV, "")
)
if self.authenticate is None:
self.authenticate = _flag(os.environ.get(AUTHENTICATE_ENV)) or _hosted(
self.url
Expand All @@ -219,6 +232,9 @@ def __post_init__(self):
if self.user and not self.user_id:
self.user_id = str(self.user.get("id", ""))

if self.private_key:
return

# Falling back to the customer header would send a request the proxy refuses, and
# report it as whatever the proxy says rather than as what it is. Checked here rather
# than at first use because it is a contradiction in what was passed.
Expand All @@ -245,7 +261,11 @@ def server_side(self) -> bool:
accessible, which is everything about how an agent is configured and the claiming of
a guest. Worth asking before a call rather than reading a 403 afterwards.
"""
return bool(self.api_secret) or (not self.api_key and bool(self.customer_id))
return (
bool(self.private_key)
or bool(self.api_secret)
or (not self.api_key and bool(self.customer_id))
)

def as_user(self, user: Union[str, dict[str, object]], token: str) -> "Backend":
"""A backend acting for one end user, holding the token that proves it.
Expand Down Expand Up @@ -294,7 +314,7 @@ def _category_header(self) -> dict[str, str]:

Behind the proxy they are on the token, and the proxy deletes the header.
"""
if self.authenticate or not (self.team or self.usage_categories):
if self.private_key or self.authenticate or not (self.team or self.usage_categories):
return {}
named = list(self.usage_categories)
if self.team:
Expand Down Expand Up @@ -335,6 +355,8 @@ def user_token(

def _credentials(self) -> dict[str, str]:
"""Who is calling, as headers."""
if self.private_key:
return {"Authorization": f"Bearer {self._ed25519_token()}"}
if not self.api_key:
return {CUSTOMER_HEADER: str(self.customer_id)}

Expand Down Expand Up @@ -367,7 +389,20 @@ def client(self) -> AuthenticatedClient:
headers. Built per call rather than kept, which is also what keeps a minted token
fresh. An answer outside 2xx raises RouterError before anything parses it.
"""
refusals = {"event_hooks": {"response": [raise_refusal]}}
refusals: dict[str, object] = {"event_hooks": {"response": [raise_refusal]}}
if self.private_key:
credentials = dict(self.headers)
authorization = credentials.pop("Authorization", "")
if self.api_key:
refusals["params"] = {"api_key": str(self.api_key)}
return AuthenticatedClient(
base_url=str(self.url),
token=authorization.removeprefix("Bearer "),
auth_header_name="Authorization",
prefix="Bearer",
headers=credentials,
httpx_args=refusals,
)
if not self.api_key:
headers = self._category_header()
headers[CLIENT_HEADER] = CLIENT_SDK
Expand Down Expand Up @@ -402,10 +437,17 @@ def socket(self, path: str) -> str:
"""
base = str(self.url)
if base.startswith("https://"):
return "wss://" + base[len("https://") :] + path
if base.startswith("http://"):
return "ws://" + base[len("http://") :] + path
return base + path
target = "wss://" + base[len("https://") :] + path
elif base.startswith("http://"):
target = "ws://" + base[len("http://") :] + path
else:
target = base + path
if self.private_key and self.api_key:
parts = urlsplit(target)
query = dict(parse_qsl(parts.query, keep_blank_values=True))
query["api_key"] = str(self.api_key)
return urlunsplit(parts._replace(query=urlencode(query)))
return target

def stream_credentials(self) -> Optional[dict[str, object]]:
"""What Stream's own chat and video clients need to connect, or None.
Expand All @@ -432,6 +474,19 @@ def stream_credentials(self) -> Optional[dict[str, object]]:
),
}

def _ed25519_token(self) -> str:
claims: dict[str, object] = {**self._category_claims()}
if self.customer_id:
claims["customer_id"] = self.customer_id
if self.app_id:
claims["app_id"] = self.app_id
if self.user_id:
claims["kind"] = "authenticated"
claims["user_id"] = self.user_id
else:
claims["kind"] = "server"
return _sign_ed25519(claims, self.private_key)

def _server_token(self) -> str:
"""A token that speaks for the app itself, which is Stream's ``server: true``.

Expand Down Expand Up @@ -503,6 +558,30 @@ def _sign(
return signing + "." + _b64(mac)


def _load_ed25519_private_key(private_key_pem: str) -> Ed25519PrivateKey:
key = load_pem_private_key(private_key_pem.encode(), password=None)
if not isinstance(key, Ed25519PrivateKey):
raise ValueError("private_key must be a PEM-encoded Ed25519 private key")
return key


def _sign_ed25519(
claims: dict[str, object],
private_key_pem: str,
validity_seconds: int = TOKEN_VALIDITY_SECONDS,
) -> str:
key = _load_ed25519_private_key(private_key_pem)
issued = int(time.time())
payload = {"iat": issued, "exp": issued + validity_seconds, **claims}
signing = (
_b64(json.dumps({"alg": "EdDSA", "typ": "JWT"}, separators=(",", ":")).encode())
+ "."
+ _b64(json.dumps(payload, separators=(",", ":")).encode())
)
signature = key.sign(signing.encode())
return signing + "." + _b64(signature)


def _b64(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()

Expand Down
4 changes: 3 additions & 1 deletion sdks/dart/stream_agents/lib/src/core/socket.dart
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@ final class SessionSocket {
if (_socket != null) {
throw StateError('the socket is already open');
}
final connecting = WebSocket.connect(uri);
final token = uri.queryParameters['token'];
final protocols = token != null && token.isNotEmpty ? ['bearer', token] : null;
final connecting = WebSocket.connect(uri, protocols: protocols);
final WebSocket socket;
try {
socket = await connecting.timeout(_opening);
Expand Down
7 changes: 2 additions & 5 deletions sdks/go/stream/accelerated.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,11 +476,8 @@ func (p *Pipeline) Watch(ctx context.Context, session *acceleration.Session) err
}

func (p *Pipeline) socketFor(backend Backend, credentials http.Header, id string, asked url.Values) *Socket {
address := backend.SocketURL("/v1/agents/sessions/" + id + "/events")
if len(asked) > 0 {
address += "?" + asked.Encode()
}
return NewSocket(address, credentials, backend.HTTPClient, p.logger)
return NewSocket(backend.socketAddress("/v1/agents/sessions/"+id+"/events", asked),
credentials, backend.HTTPClient, p.logger)
}

// ready waits for a running Leave to finish, then returns the client to join with.
Expand Down
Loading