From b7d56940a7f804760d3003ab0ca204cd1676229e Mon Sep 17 00:00:00 2001 From: thesyncim Date: Tue, 1 Dec 2026 09:54:52 +0000 Subject: [PATCH] feat(sdks): add Ed25519 (EdDSA) jwt auth support across SDKs --- .../sdk/notes/2026-12-01-ed25519-jwt-auth.md | 12 + plugins/stream/pyproject.toml | 1 + plugins/stream/tests/test_ed25519_backend.py | 89 +++++++ .../vision_agents/plugins/stream/_backend.py | 95 +++++++- .../stream_agents/lib/src/core/socket.dart | 4 +- sdks/go/stream/accelerated.go | 7 +- sdks/go/stream/backend.go | 93 +++++++- sdks/go/stream/dispatch.go | 2 +- sdks/go/stream/jwt_test.go | 147 ++++++++++++ sdks/go/stream/router.go | 2 +- sdks/js/src/backend.ts | 93 +++++++- sdks/js/tests/ed25519.test.ts | 78 +++++++ sdks/php/src/Backend.php | 76 +++++- sdks/php/src/Client.php | 3 + sdks/php/tests/Unit/Ed25519BackendTest.php | 84 +++++++ .../lib/getstream/vision_agents/backend.rb | 65 +++++- .../lib/getstream/vision_agents/client.rb | 3 + sdks/ruby/test/ed25519_test.rb | 60 +++++ sdks/rust/Cargo.lock | 1 + sdks/rust/Cargo.toml | 1 + sdks/rust/src/backend.rs | 221 ++++++++++++++++-- sdks/rust/src/client.rs | 5 + uv.lock | 2 + 23 files changed, 1082 insertions(+), 62 deletions(-) create mode 100644 .claude/skills/sdk/notes/2026-12-01-ed25519-jwt-auth.md create mode 100644 plugins/stream/tests/test_ed25519_backend.py create mode 100644 sdks/go/stream/jwt_test.go create mode 100644 sdks/js/tests/ed25519.test.ts create mode 100644 sdks/php/tests/Unit/Ed25519BackendTest.php create mode 100644 sdks/ruby/test/ed25519_test.rb diff --git a/.claude/skills/sdk/notes/2026-12-01-ed25519-jwt-auth.md b/.claude/skills/sdk/notes/2026-12-01-ed25519-jwt-auth.md new file mode 100644 index 0000000000..a1a88d5faf --- /dev/null +++ b/.claude/skills/sdk/notes/2026-12-01-ed25519-jwt-auth.md @@ -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 ` and public `api_key` as query parameter (`?api_key=...`). +- **WebSocket:** + - Server-side SDKs send `Authorization: Bearer ` and `?api_key=...`. + - Browser / client-side SDKs send `Sec-WebSocket-Protocol: bearer, ` 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). diff --git a/plugins/stream/pyproject.toml b/plugins/stream/pyproject.toml index 66e7fc18fa..be510b9144 100644 --- a/plugins/stream/pyproject.toml +++ b/plugins/stream/pyproject.toml @@ -15,6 +15,7 @@ dependencies = [ "aiohttp>=3.10", "httpx>=0.27", "attrs>=23.2", + "cryptography>=44.0.0", "pyyaml>=6.0", ] diff --git a/plugins/stream/tests/test_ed25519_backend.py b/plugins/stream/tests/test_ed25519_backend.py new file mode 100644 index 0000000000..e203bb4e37 --- /dev/null +++ b/plugins/stream/tests/test_ed25519_backend.py @@ -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"] diff --git a/plugins/stream/vision_agents/plugins/stream/_backend.py b/plugins/stream/vision_agents/plugins/stream/_backend.py index 89ce710338..bd41e9a66c 100644 --- a/plugins/stream/vision_agents/plugins/stream/_backend.py +++ b/plugins/stream/vision_agents/plugins/stream/_backend.py @@ -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 @@ -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 @@ -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 @@ -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. @@ -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. @@ -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: @@ -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)} @@ -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 @@ -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. @@ -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``. @@ -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() diff --git a/sdks/dart/stream_agents/lib/src/core/socket.dart b/sdks/dart/stream_agents/lib/src/core/socket.dart index f1a9ea04b8..aa3563bde8 100644 --- a/sdks/dart/stream_agents/lib/src/core/socket.dart +++ b/sdks/dart/stream_agents/lib/src/core/socket.dart @@ -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); diff --git a/sdks/go/stream/accelerated.go b/sdks/go/stream/accelerated.go index 33299d8f08..35fb2bc198 100644 --- a/sdks/go/stream/accelerated.go +++ b/sdks/go/stream/accelerated.go @@ -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. diff --git a/sdks/go/stream/backend.go b/sdks/go/stream/backend.go index e2b3d17afa..ef847799ae 100644 --- a/sdks/go/stream/backend.go +++ b/sdks/go/stream/backend.go @@ -4,9 +4,12 @@ package stream import ( "context" + "crypto/ed25519" "errors" "fmt" + "maps" "net/http" + "net/url" "os" "regexp" "slices" @@ -134,6 +137,9 @@ type Backend struct { // back to STREAM_ACCELERATION_CUSTOMER_ID. A router behind the authenticating proxy // works this out from the credential instead and ignores what it is told. CustomerID string + // AppID is the app claim written into Ed25519 JWTs when talking directly to a router + // without a gateway (in api_key mode the router resolves it from api_key instead). + AppID string // Authenticate says the router is reached through the proxy, so requests carry the app // credential below rather than naming a customer. It is on whenever no customer id is // set, whenever the router is the hosted one, and whenever a credential is passed in, @@ -142,6 +148,10 @@ type Backend struct { // APIKey and APISecret are the Stream app to authenticate as. Empty falls back to STREAM_API_KEY and STREAM_API_SECRET. APIKey string APISecret string + // PrivateKey is a PEM-encoded PKCS#8 Ed25519 private key used to sign EdDSA JWTs. + // When set, requests send Authorization: Bearer and api_key in the query string + // instead of legacy HS256 headers. + PrivateKey string // UserID is the end user this SDK is acting for, if it is acting for one. Empty speaks // for the app itself, which is what a backend does, and is what keeps the per-user // daily limits out of it. @@ -227,10 +237,19 @@ func (b Backend) Resolve() (Backend, error) { // credential to a router with nothing in front of it reads as an end user's device. // What does not depend on the environment does say: the hosted router, in any region, // is always behind the proxy, and a credential passed in was passed in to be used. - passed := b.APIKey != "" && (b.APISecret != "" || b.Token != "") + passed := b.PrivateKey != "" || (b.APIKey != "" && (b.APISecret != "" || b.Token != "")) if b.CustomerID == "" || hosted(b.URL) || passed { b.Authenticate = true } + if b.PrivateKey != "" { + if _, err := parseEd25519PrivateKey(b.PrivateKey); err != nil { + return b, err + } + if b.APIKey == "" { + b.APIKey = os.Getenv(APIKeyEnv) + } + return b, nil + } if b.Authenticate { if b.APIKey == "" { b.APIKey = os.Getenv(APIKeyEnv) @@ -247,6 +266,18 @@ func (b Backend) Resolve() (Backend, error) { return b, nil } +func parseEd25519PrivateKey(pemKey string) (ed25519.PrivateKey, error) { + parsed, err := jwt.ParseEdPrivateKeyFromPEM([]byte(strings.TrimSpace(pemKey))) + if err != nil { + return nil, fmt.Errorf("stream: parse Ed25519 private key: %w", err) + } + key, ok := parsed.(ed25519.PrivateKey) + if !ok { + return nil, errors.New("stream: private key is not an Ed25519 key") + } + return key, nil +} + // token mints what the proxy verifies: a token signed with the app's secret, naming a user // only when this SDK is acting for one. // @@ -261,17 +292,40 @@ func (b Backend) token() (string, error) { "iat": jwt.NewNumericDate(now), "exp": jwt.NewNumericDate(now.Add(tokenValidity)), } - if b.UserID == "" { - claims["server"] = true - } else { - claims["user_id"] = b.UserID - } if b.Team != "" { claims["team"] = b.Team } if len(b.UsageCategories) > 0 { claims["usage_categories"] = b.UsageCategories } + if b.PrivateKey != "" { + key, err := parseEd25519PrivateKey(b.PrivateKey) + if err != nil { + return "", err + } + if b.CustomerID != "" { + claims["customer_id"] = b.CustomerID + } + if b.AppID != "" { + claims["app_id"] = b.AppID + } + if b.UserID == "" { + claims["kind"] = "server" + } else { + claims["kind"] = "authenticated" + claims["user_id"] = b.UserID + } + signed, err := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims).SignedString(key) + if err != nil { + return "", fmt.Errorf("stream: signing an Ed25519 token: %w", err) + } + return signed, nil + } + if b.UserID == "" { + claims["server"] = true + } else { + claims["user_id"] = b.UserID + } signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(b.APISecret)) if err != nil { return "", fmt.Errorf("stream: signing a token for %s: %w", b.APIKey, err) @@ -301,6 +355,10 @@ func (b Backend) Credentials() (http.Header, error) { if err != nil { return nil, err } + if b.PrivateKey != "" { + header.Set("Authorization", "Bearer "+token) + return header, nil + } header.Set(APIKeyHeader, b.APIKey) header.Set(AuthTypeHeader, AuthTypeJWT) header.Set(AuthorizationHeader, token) @@ -375,6 +433,11 @@ func (b Backend) Client() (*acceleration.ClientWithResponses, error) { for name, values := range credentials { request.Header[name] = values } + if resolved.PrivateKey != "" && resolved.APIKey != "" { + q := request.URL.Query() + q.Set(APIKeyHeader, resolved.APIKey) + request.URL.RawQuery = q.Encode() + } return nil }), } @@ -392,3 +455,21 @@ func (b Backend) SocketURL(path string) string { return b.URL + path } } + +func (b Backend) socketAddress(path string, query url.Values) string { + address := b.SocketURL(path) + var q url.Values + if len(query) > 0 { + q = maps.Clone(query) + } + if b.PrivateKey != "" && b.APIKey != "" { + if q == nil { + q = url.Values{} + } + q.Set(APIKeyHeader, b.APIKey) + } + if len(q) > 0 { + return address + "?" + q.Encode() + } + return address +} diff --git a/sdks/go/stream/dispatch.go b/sdks/go/stream/dispatch.go index 08e15d606c..c43c30333c 100644 --- a/sdks/go/stream/dispatch.go +++ b/sdks/go/stream/dispatch.go @@ -396,7 +396,7 @@ func (d *Dispatch) connect(ctx context.Context, backend Backend) (*Socket, error if err != nil { return nil, err } - socket := NewSocket(backend.SocketURL(DispatchPath)+"?"+d.waiting().Encode(), + socket := NewSocket(backend.socketAddress(DispatchPath, d.waiting()), credentials, backend.HTTPClient, d.logger) if err := socket.Open(ctx); err != nil { return nil, err diff --git a/sdks/go/stream/jwt_test.go b/sdks/go/stream/jwt_test.go new file mode 100644 index 0000000000..03bdf799db --- /dev/null +++ b/sdks/go/stream/jwt_test.go @@ -0,0 +1,147 @@ +package stream + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "encoding/pem" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/suite" +) + +type Ed25519AuthSuite struct { + suite.Suite + publicKey ed25519.PublicKey + privateKeyPEM string +} + +func TestEd25519AuthSuite(t *testing.T) { + suite.Run(t, new(Ed25519AuthSuite)) +} + +func (s *Ed25519AuthSuite) SetupTest() { + pub, priv, err := ed25519.GenerateKey(rand.Reader) + s.Require().NoError(err) + + der, err := x509.MarshalPKCS8PrivateKey(priv) + s.Require().NoError(err) + + s.publicKey = pub + s.privateKeyPEM = string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})) +} + +func (s *Ed25519AuthSuite) parseBearer(header http.Header) jwt.MapClaims { + s.T().Helper() + raw, ok := strings.CutPrefix(header.Get("Authorization"), "Bearer ") + s.Require().True(ok, "expected Authorization: Bearer , got %q", header.Get("Authorization")) + + claims := jwt.MapClaims{} + _, err := jwt.ParseWithClaims(raw, claims, + func(*jwt.Token) (any, error) { return s.publicKey, nil }, + jwt.WithValidMethods([]string{jwt.SigningMethodEdDSA.Alg()}), + jwt.WithExpirationRequired(), + ) + s.Require().NoError(err) + return claims +} + +func (s *Ed25519AuthSuite) TestInvalidPrivateKeyIsRefusedAtResolve() { + _, err := Backend{URL: "http://localhost:8080", PrivateKey: "not-a-key"}.Resolve() + s.Require().Error(err) +} + +func (s *Ed25519AuthSuite) TestServerCredentialsSignEdDSAWithBearerHeader() { + resolved, err := Backend{ + URL: "http://localhost:8080", + APIKey: "pub-key", + CustomerID: "org-1", + AppID: "app-1", + PrivateKey: s.privateKeyPEM, + Team: "sales", + UsageCategories: []string{"support"}, + }.Resolve() + s.Require().NoError(err) + + headers, err := resolved.Credentials() + s.Require().NoError(err) + s.Empty(headers.Get(APIKeyHeader)) + s.Empty(headers.Get(AuthTypeHeader)) + + claims := s.parseBearer(headers) + s.Equal("org-1", claims["customer_id"]) + s.Equal("app-1", claims["app_id"]) + s.Equal("server", claims["kind"]) + s.Equal("sales", claims["team"]) + s.Equal([]any{"support"}, claims["usage_categories"]) + s.NotContains(claims, "user_id") +} + +func (s *Ed25519AuthSuite) TestClientCredentialsSetClientAuthTypeAndUserID() { + resolved, err := Backend{ + URL: "http://localhost:8080", + APIKey: "pub-key", + CustomerID: "org-1", + AppID: "app-1", + UserID: "user-42", + PrivateKey: s.privateKeyPEM, + }.Resolve() + s.Require().NoError(err) + + headers, err := resolved.Credentials() + s.Require().NoError(err) + + claims := s.parseBearer(headers) + s.Equal("authenticated", claims["kind"]) + s.Equal("user-42", claims["user_id"]) +} + +func (s *Ed25519AuthSuite) TestClientSendsBearerHeaderAndAPIKeyQueryParam() { + var gotHeader http.Header + var gotQuery url.Values + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotHeader = r.Header.Clone() + gotQuery = r.URL.Query() + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{}`)) + })) + defer server.Close() + + api, err := Backend{ + URL: server.URL, + APIKey: "pub-key", + CustomerID: "org-1", + AppID: "app-1", + PrivateKey: s.privateKeyPEM, + }.Client() + s.Require().NoError(err) + + _, err = api.GetAppSettingsWithResponse(s.T().Context()) + s.Require().NoError(err) + s.Equal("pub-key", gotQuery.Get("api_key")) + + claims := s.parseBearer(gotHeader) + s.Equal("server", claims["kind"]) + s.Equal("app-1", claims["app_id"]) +} + +func (s *Ed25519AuthSuite) TestSocketAddressAttachesAPIKeyPreservingQuery() { + backend := Backend{ + URL: "https://router.example.com", + APIKey: "pub-key", + PrivateKey: s.privateKeyPEM, + } + + got := backend.socketAddress("/v1/dispatch", url.Values{"capacity": {"4"}}) + parsed, err := url.Parse(got) + s.Require().NoError(err) + s.Equal("wss", parsed.Scheme) + s.Equal("/v1/dispatch", parsed.Path) + s.Equal("4", parsed.Query().Get("capacity")) + s.Equal("pub-key", parsed.Query().Get("api_key")) +} diff --git a/sdks/go/stream/router.go b/sdks/go/stream/router.go index 89cb0a7767..caa36c67dd 100644 --- a/sdks/go/stream/router.go +++ b/sdks/go/stream/router.go @@ -708,7 +708,7 @@ func (r Router) open(ctx context.Context, modality string, options Frame) (*Sock return nil, err } socket := NewSocket( - backend.SocketURL("/v1/"+modality+"/stream"), + backend.socketAddress("/v1/"+modality+"/stream", nil), credentials, backend.HTTPClient, r.logger(), diff --git a/sdks/js/src/backend.ts b/sdks/js/src/backend.ts index a0973d8fbb..8dbb1511eb 100644 --- a/sdks/js/src/backend.ts +++ b/sdks/js/src/backend.ts @@ -222,6 +222,11 @@ export interface BackendOptions { * `STREAM_ACCELERATION_CUSTOMER_ID`. */ customerId?: string; + /** + * The app claim written into Ed25519 JWTs when talking directly to a router without a + * gateway (in api_key mode the router resolves it from `apiKey` instead). + */ + appId?: string; /** * The public half of a Stream credential. Falls back to `STREAM_API_KEY`. * @@ -237,6 +242,12 @@ export interface BackendOptions { * Falls back to `STREAM_API_SECRET`. */ apiSecret?: string; + /** + * PEM-encoded PKCS#8 Ed25519 private key used to sign EdDSA JWTs. + * Server side only. When set, requests send `Authorization: Bearer ` and `api_key` + * in the query string instead of legacy HS256 headers. + */ + privateKey?: string; /** * A token an app's own backend minted for this end user to hold. * @@ -322,6 +333,7 @@ export interface BackendOptions { export class Backend { readonly url: string; readonly customerId: string; + readonly appId: string; readonly apiKey: string; /** Whether the credential is spelled for Stream's proxy rather than for the router. */ readonly authenticate: boolean; @@ -335,6 +347,7 @@ export class Backend { readonly timeoutMs: number; /** Whether the router is told the customer rather than shown a credential. */ private readonly byCustomer: boolean; + private readonly privateKey: string; /** * Mutable, and `declaredSecret` is what says whether it may be dropped: a secret that was * passed is the caller's own claim to be the app's backend, and one that was only lying @@ -377,6 +390,8 @@ export class Backend { } this.url = routerUrl(options).replace(/\/+$/, ""); this.customerId = options.customerId ?? env(CUSTOMER_ENV) ?? ""; + this.appId = options.appId ?? ""; + this.privateKey = options.privateKey?.trim() ?? ""; // The same reasoning as the secret below: naming a customer is choosing the way a // router with nothing in front of it is reached, and a key that happens to be in the // environment does not overrule the choice. Otherwise pointing a client at a local @@ -387,7 +402,7 @@ export class Backend { // secret does not overrule it. Without this a client built the way a browser 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. - this.apiSecret = options.apiSecret ?? (options.token ? "" : env(API_SECRET_ENV) ?? ""); + this.apiSecret = options.apiSecret ?? (options.token || this.privateKey ? "" : env(API_SECRET_ENV) ?? ""); this.declaredSecret = Boolean(options.apiSecret); this.token = options.token; this.userIdValue = options.userId ?? ""; @@ -408,7 +423,7 @@ export class Backend { // A customer that was named is chosen over a key that was also passed, because the key // is then there for Stream's own clients. The proxy reads no customer, so it never is. this.byCustomer = - !this.authenticate && Boolean(this.customerId) && (Boolean(options.customerId) || !this.apiKey); + !this.privateKey && !this.authenticate && Boolean(this.customerId) && (Boolean(options.customerId) || !this.apiKey); this.webSocketImpl = options.webSocket ?? globalWebSocket(); // Bound, because a browser only lets fetch be called on the window: kept as a field and @@ -425,7 +440,7 @@ export class Backend { // report it as whatever the proxy says rather than as what it is. This one is checked // here rather than at first use because it is a contradiction in what was passed, not a // credential that has yet to arrive. - if (this.authenticate && !this.apiKey) { + if (this.authenticate && !this.apiKey && !this.privateKey) { throw new ConfigurationError( `a router behind the proxy is reached with a credential; pass apiKey, or ${API_KEY_ENV}`, ); @@ -589,6 +604,9 @@ export class Backend { * `setUser`, and throwing on that line would make the shape impossible to write. */ private assertCredentialed(): void { + if (this.privateKey) { + return; + } if (!this.apiKey && !this.customerId) { throw new ConfigurationError( `who is calling is not set; pass customerId or ${CUSTOMER_ENV} for a router that ` + @@ -610,6 +628,9 @@ export class Backend { * before a call rather than reading a 403 afterwards. */ get serverSide(): boolean { + if (this.privateKey) { + return true; + } // A router reached by customer id is never shown the secret, so there it is what the // requests say that counts: a page names its user and is that user. return this.byCustomer ? !this.isPage : Boolean(this.apiSecret); @@ -631,7 +652,7 @@ export class Backend { * guest is asked for before there is one: `stream-auth-type: anonymous` and no token. */ get anonymous(): boolean { - return Boolean(this.apiKey) && !this.byCustomer && !this.apiSecret && !this.token; + return Boolean(this.apiKey) && !this.byCustomer && !this.apiSecret && !this.privateKey && !this.token; } /** @@ -654,6 +675,12 @@ export class Backend { : { "X-Api-Key": this.apiKey, "Stream-Auth-Type": "anonymous" }; } this.assertCredentialed(); + if (this.privateKey) { + return { + Authorization: `Bearer ${await this.ed25519Token()}`, + ...(this.actingForValue ? { "X-Stream-User-Id": this.actingForValue } : {}), + }; + } const beside: Record = { ...(this.actingForValue ? { "X-Stream-User-Id": this.actingForValue } : {}), ...this.categoryHeader(), @@ -706,6 +733,12 @@ export class Backend { url.searchParams.set(name, value); } + if (this.privateKey) { + if (this.apiKey) { + url.searchParams.set("api_key", this.apiKey); + } + return url.toString(); + } if (!this.byCustomer) { if (!this.socketCarriesHeaders) { const token = this.authenticate ? await this.proxyToken() : await this.userToken(); @@ -747,6 +780,9 @@ export class Backend { return undefined; } this.assertCredentialed(); + if (this.privateKey) { + return { Authorization: `Bearer ${await this.ed25519Token()}` }; + } if (this.authenticate) { return { api_key: this.apiKey, @@ -763,7 +799,7 @@ export class Backend { /** Whether sockets carry the credential as headers: see `socketHeaders`. */ private get socketCarriesHeaders(): boolean { - return !this.byCustomer && Boolean(this.apiSecret); + return Boolean(this.privateKey) || (!this.byCustomer && Boolean(this.apiSecret)); } /** @@ -785,6 +821,7 @@ export class Backend { ...(this.team ? { team: this.team } : {}), ...(this.usageCategories.length > 0 ? { usageCategories: [...this.usageCategories] } : {}), ...(this.apiSecret ? { apiSecret: REDACTED } : {}), + ...(this.privateKey ? { privateKey: REDACTED } : {}), ...(this.token ? { token: REDACTED } : {}), }; } @@ -829,6 +866,9 @@ export class Backend { * gives. */ query(): Record { + if (this.privateKey) { + return this.apiKey ? { api_key: this.apiKey } : {}; + } if (!this.byCustomer || !this.userId) { return {}; } @@ -881,6 +921,16 @@ export class Backend { * It names no user by definition: one that named a user would be a token minted for that * user to hold. Which of its users a backend is acting for goes in a header instead. */ + private ed25519Token(): Promise { + const claims: Record = { + ...(this.customerId ? { customer_id: this.customerId } : {}), + ...(this.appId ? { app_id: this.appId } : {}), + ...(this.userId ? { kind: "authenticated", user_id: this.userId } : { kind: "server" }), + ...this.categoryClaims(), + }; + return signEd25519Token(claims, this.privateKey); + } + private serverToken(): Promise { return this.mint({ server: true, ...this.categoryClaims() }); } @@ -1063,6 +1113,39 @@ export async function signToken( return `${signing}.${base64urlBytes(new Uint8Array(mac))}`; } +/** Signs an EdDSA (Ed25519) JWT using Web Crypto with a PEM-encoded PKCS#8 private key. */ +export async function signEd25519Token( + claims: Record, + privateKeyPem: string, + validitySeconds = TOKEN_VALIDITY_SECONDS, +): Promise { + if (!privateKeyPem) { + throw new ConfigurationError("an Ed25519 token cannot be signed without a private key"); + } + const issued = Math.floor(Date.now() / 1000); + const payload = { iat: issued, exp: issued + validitySeconds, ...claims }; + const signing = `${base64url(JSON.stringify({ alg: "EdDSA", typ: "JWT" }))}.${base64url( + JSON.stringify(payload), + )}`; + + const key = await crypto.subtle.importKey("pkcs8", pemToDer(privateKeyPem), "Ed25519", false, ["sign"]); + const signature = await crypto.subtle.sign("Ed25519", key, new TextEncoder().encode(signing)); + return `${signing}.${base64urlBytes(new Uint8Array(signature))}`; +} + +function pemToDer(pem: string): ArrayBuffer { + const b64 = pem + .replace(/-----BEGIN [^-]+-----/g, "") + .replace(/-----END [^-]+-----/g, "") + .replace(/\s+/g, ""); + const binary = atob(b64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes.buffer; +} + function base64url(text: string): string { return base64urlBytes(new TextEncoder().encode(text)); } diff --git a/sdks/js/tests/ed25519.test.ts b/sdks/js/tests/ed25519.test.ts new file mode 100644 index 0000000000..0496b867e4 --- /dev/null +++ b/sdks/js/tests/ed25519.test.ts @@ -0,0 +1,78 @@ +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import { describe, it } from "node:test"; +import { Backend, REDACTED } from "../src/backend.js"; + +function generateEd25519Pair() { + const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519"); + return { + publicKey, + privateKeyPem: privateKey.export({ type: "pkcs8", format: "pem" }).toString(), + }; +} + +function verifyBearer(authHeader: string | undefined, publicKey: crypto.KeyObject): Record { + if (!authHeader?.startsWith("Bearer ")) { + assert.fail(`expected Bearer header, got ${authHeader}`); + } + const token = authHeader.slice("Bearer ".length); + const [rawHeader, rawPayload, rawSig] = token.split("."); + assert.ok(rawHeader && rawPayload && rawSig, "expected 3 JWT segments"); + const header = JSON.parse(Buffer.from(rawHeader, "base64url").toString("utf8")) as { alg: string }; + assert.equal(header.alg, "EdDSA"); + const ok = crypto.verify(null, Buffer.from(`${rawHeader}.${rawPayload}`), publicKey, Buffer.from(rawSig, "base64url")); + assert.equal(ok, true, "Ed25519 signature must verify"); + return JSON.parse(Buffer.from(rawPayload, "base64url").toString("utf8")) as Record; +} + +describe("Ed25519 JWT auth", () => { + it("signs server EdDSA JWT with Bearer header and api_key query param", async () => { + const { publicKey, privateKeyPem } = generateEd25519Pair(); + const backend = new Backend({ + url: "http://localhost:8080", + apiKey: "pub-key", + customerId: "org-1", + appId: "app-1", + privateKey: privateKeyPem, + team: "sales", + usageCategories: ["support"], + }); + + assert.equal(backend.serverSide, true); + assert.equal(backend.toJSON().privateKey, REDACTED); + assert.deepEqual(backend.query(), { api_key: "pub-key" }); + + const headers = await backend.headers(); + assert.equal(headers["api_key"], undefined); + assert.equal(headers["X-Api-Key"], undefined); + + const claims = verifyBearer(headers["Authorization"], publicKey); + assert.equal(claims.customer_id, "org-1"); + assert.equal(claims.app_id, "app-1"); + assert.equal(claims.kind, "server"); + assert.equal(claims.team, "sales"); + assert.deepEqual(claims.usage_categories, ["support"]); + }); + + it("signs client EdDSA JWT when userId is set and attaches api_key on socketURL", async () => { + const { publicKey, privateKeyPem } = generateEd25519Pair(); + const backend = new Backend({ + url: "https://router.example.com", + apiKey: "pub-key", + customerId: "org-1", + appId: "app-1", + userId: "user-42", + privateKey: privateKeyPem, + }); + + const socketHeaders = await backend.socketHeaders(); + const claims = verifyBearer(socketHeaders?.["Authorization"], publicKey); + assert.equal(claims.kind, "authenticated"); + assert.equal(claims.user_id, "user-42"); + + const wsUrl = new URL(await backend.socketURL("/v1/dispatch", { capacity: "4" })); + assert.equal(wsUrl.protocol, "wss:"); + assert.equal(wsUrl.searchParams.get("api_key"), "pub-key"); + assert.equal(wsUrl.searchParams.get("capacity"), "4"); + }); +}); diff --git a/sdks/php/src/Backend.php b/sdks/php/src/Backend.php index 5ddf00fad0..88cf2a59ee 100644 --- a/sdks/php/src/Backend.php +++ b/sdks/php/src/Backend.php @@ -42,6 +42,7 @@ public string $url; public string $customerId; + public string $appId; public string $apiKey; public string $userId; /** The end user this backend speaks for while keeping its own server credential. */ @@ -52,6 +53,7 @@ /** @var list the customer's own groupings the work is counted against, sorted, each once */ public array $usageCategories; private string $apiSecret; + private string $privateKey; private string $token; /** @@ -94,6 +96,8 @@ public function __construct( ?string $region = null, ?string $team = null, array $usageCategories = [], + string $appId = '', + string $privateKey = '', ) { $this->team = $team === '' ? null : $team; $this->usageCategories = UsageCategories::checked($this->team, $usageCategories); @@ -102,23 +106,33 @@ public function __construct( } $this->url = rtrim(self::locate($url, $region), '/'); $this->customerId = $customerId ?? self::env(self::CUSTOMER_ENV) ?? ''; + $this->appId = $appId; + $this->privateKey = trim($privateKey); + if ($this->privateKey !== '') { + self::ed25519SeedFromPem($this->privateKey); + } // Naming a customer is choosing how a router with nothing in front of it is reached, // and a key that happens to be in the environment does not overrule the choice. $this->apiKey = $apiKey ?? ($customerId !== null ? '' : (self::env(self::API_KEY_ENV) ?? '')); // A token handed in is the caller's answer to who they are, so an ambient secret does // not turn it back into a backend. - $this->apiSecret = $apiSecret ?? ($token !== '' || $this->apiKey === '' ? '' : (self::env(self::API_SECRET_ENV) ?? '')); + $this->apiSecret = $apiSecret ?? ($token !== '' || $this->privateKey !== '' || $this->apiKey === '' ? '' : (self::env(self::API_SECRET_ENV) ?? '')); $this->token = $token; $this->userId = $userId; $this->onBehalfOf = $onBehalfOf; $this->authenticate = $authenticate ?? (self::flag(self::env(self::AUTHENTICATE_ENV)) || self::hosted($this->url)); - if ($this->authenticate && $this->apiKey === '') { + if ($this->privateKey === '' && $this->authenticate && $this->apiKey === '') { throw new ConfigurationException('a router behind the proxy is reached with a credential; pass apiKey, or ' . self::API_KEY_ENV); } } + public function usesEd25519(): bool + { + return $this->privateKey !== ''; + } + /** * Whether this speaks for a process the customer runs rather than for a device. * @@ -127,7 +141,7 @@ public function __construct( */ public function serverSide(): bool { - return $this->apiSecret !== '' || ($this->apiKey === '' && $this->customerId !== ''); + return $this->privateKey !== '' || $this->apiSecret !== '' || ($this->apiKey === '' && $this->customerId !== ''); } /** @@ -231,6 +245,12 @@ public function userToken(string $userId, ?string $team = null, array $usageCate */ public function headers(): array { + if ($this->privateKey !== '') { + return [ + 'Authorization' => 'Bearer ' . $this->ed25519Token(), + ...($this->onBehalfOf !== '' ? ['X-Stream-User-Id' => $this->onBehalfOf] : []), + ]; + } if ($this->apiKey === '') { if ($this->customerId === '') { throw new ConfigurationException( @@ -274,10 +294,60 @@ public function headers(): array */ public function socketUrl(string $path, array $query = []): string { + if ($this->privateKey !== '' && $this->apiKey !== '') { + $query['api_key'] = $this->apiKey; + } $url = preg_replace('#^http#', 'ws', $this->url) . $path; return $query === [] ? $url : $url . '?' . http_build_query($query); } + /** + * Signs an EdDSA (Ed25519) JWT using a PEM-encoded PKCS#8 private key. + * + * @param array $claims + */ + public static function signEd25519(array $claims, string $privateKeyPem, int $validitySeconds = self::TOKEN_VALIDITY_SECONDS): string + { + $seed = self::ed25519SeedFromPem($privateKeyPem); + $keypair = sodium_crypto_sign_seed_keypair($seed); + $secretKey = sodium_crypto_sign_secretkey($keypair); + $issued = time(); + $payload = ['iat' => $issued, 'exp' => $issued + $validitySeconds, ...$claims]; + $signing = self::base64url(Json::encode(['alg' => 'EdDSA', 'typ' => 'JWT'])) . '.' . self::base64url(Json::encode($payload)); + $sig = sodium_crypto_sign_detached($signing, $secretKey); + return $signing . '.' . self::base64url($sig); + } + + private static function ed25519SeedFromPem(string $pem): string + { + $clean = preg_replace('/-----BEGIN [^-]+-----|-----END [^-]+-----|\s+/', '', trim($pem)); + $der = is_string($clean) ? base64_decode($clean, true) : false; + // PKCS#8 Ed25519 private key is 16-byte ASN.1 header + 32-byte raw seed. + $prefix = "\x30\x2e\x02\x01\x00\x30\x05\x06\x03\x2b\x65\x70\x04\x22\x04\x20"; + if (!is_string($der) || strlen($der) !== 48 || !str_starts_with($der, $prefix)) { + throw new ConfigurationException('privateKey must be a PEM-encoded PKCS#8 Ed25519 private key'); + } + return substr($der, 16, 32); + } + + private function ed25519Token(): string + { + $claims = $this->categoryClaims(); + if ($this->customerId !== '') { + $claims['customer_id'] = $this->customerId; + } + if ($this->appId !== '') { + $claims['app_id'] = $this->appId; + } + if ($this->userId !== '') { + $claims['kind'] = 'authenticated'; + $claims['user_id'] = $this->userId; + } else { + $claims['kind'] = 'server'; + } + return self::signEd25519($claims, $this->privateKey); + } + /** * Signs a Stream token, HS256. * diff --git a/sdks/php/src/Client.php b/sdks/php/src/Client.php index 826940f5fb..e6c310f7c8 100644 --- a/sdks/php/src/Client.php +++ b/sdks/php/src/Client.php @@ -221,6 +221,9 @@ public function delete(string $path, array $params = []): mixed public function request(string $method, string $path, array $params = [], array $query = [], array|\stdClass|null $body = null, bool $resend = true): mixed { $operation = "{$method} {$path}"; + if ($this->backend->usesEd25519() && $this->backend->apiKey !== '') { + $query['api_key'] = $this->backend->apiKey; + } $url = $this->backend->url . self::expand($path, $params) . self::queryOf($query); $request = $this->requests->createRequest($method, $url)->withHeader('Accept', 'application/json'); diff --git a/sdks/php/tests/Unit/Ed25519BackendTest.php b/sdks/php/tests/Unit/Ed25519BackendTest.php new file mode 100644 index 0000000000..917813eb77 --- /dev/null +++ b/sdks/php/tests/Unit/Ed25519BackendTest.php @@ -0,0 +1,84 @@ +publicKey = sodium_crypto_sign_publickey($kp); + $der = "\x30\x2e\x02\x01\x00\x30\x05\x06\x03\x2b\x65\x70\x04\x22\x04\x20" . $seed; + $this->privateKeyPem = "-----BEGIN PRIVATE KEY-----\n" + . chunk_split(base64_encode($der), 64, "\n") + . "-----END PRIVATE KEY-----\n"; + } + + /** @return array */ + private function verifyBearer(string $authHeader): array + { + self::assertStringStartsWith('Bearer ', $authHeader); + [$rawHeader, $rawPayload, $rawSig] = explode('.', substr($authHeader, 7)); + $header = json_decode(self::b64Decode($rawHeader), true, 512, JSON_THROW_ON_ERROR); + self::assertSame('EdDSA', $header['alg']); + $sig = self::b64Decode($rawSig); + self::assertTrue(sodium_crypto_sign_verify_detached($sig, "{$rawHeader}.{$rawPayload}", $this->publicKey)); + return json_decode(self::b64Decode($rawPayload), true, 512, JSON_THROW_ON_ERROR); + } + + private static function b64Decode(string $s): string + { + $pad = strlen($s) % 4; + if ($pad > 0) { + $s .= str_repeat('=', 4 - $pad); + } + return base64_decode(strtr($s, '-_', '+/'), true) ?: ''; + } + + public function testInvalidPrivateKeyIsRefused(): void + { + $this->expectException(ConfigurationException::class); + new Backend(url: 'http://localhost:8080', privateKey: 'not-a-key'); + } + + public function testServerAndClientCredentialsAndSocketUrl(): void + { + $backend = new Backend( + url: 'https://router.example.com', + customerId: 'org-1', + apiKey: 'pub-key', + team: 'sales', + usageCategories: ['support'], + appId: 'app-1', + privateKey: $this->privateKeyPem, + ); + + self::assertTrue($backend->serverSide()); + $headers = $backend->headers(); + self::assertArrayNotHasKey('X-Api-Key', $headers); + self::assertArrayNotHasKey('api_key', $headers); + + $claims = $this->verifyBearer($headers['Authorization']); + self::assertSame('org-1', $claims['customer_id']); + self::assertSame('app-1', $claims['app_id']); + self::assertSame('server', $claims['kind']); + self::assertSame('sales', $claims['team']); + self::assertSame(['support'], $claims['usage_categories']); + + $ws = $backend->socketUrl('/v1/dispatch', ['capacity' => '4']); + self::assertStringStartsWith('wss://router.example.com/v1/dispatch?', $ws); + parse_str((string) parse_url($ws, PHP_URL_QUERY), $params); + self::assertSame('pub-key', $params['api_key']); + self::assertSame('4', $params['capacity']); + } +} diff --git a/sdks/ruby/lib/getstream/vision_agents/backend.rb b/sdks/ruby/lib/getstream/vision_agents/backend.rb index fc02e9a8aa..383aca880a 100644 --- a/sdks/ruby/lib/getstream/vision_agents/backend.rb +++ b/sdks/ruby/lib/getstream/vision_agents/backend.rb @@ -42,7 +42,7 @@ class Backend # stolen one should stop working sooner than the credential behind it. TOKEN_VALIDITY = 60 * 60 - attr_reader :url, :customer_id, :api_key, :user_id, :user, :team, :usage_categories + attr_reader :url, :customer_id, :app_id, :api_key, :user_id, :user, :team, :usage_categories # Every argument falls back to the environment, so a process deployed next to a router # needs none of them. @@ -69,18 +69,20 @@ class Backend # the categories are signed into every token minted here, and sent in # X-Stream-Usage-Categories to a router with no proxy in front of it. A token handed in # carries the ones it was signed with, so neither can be passed with one. - def initialize(url: nil, customer_id: nil, api_key: nil, api_secret: nil, token: nil, - user_id: nil, authenticate: nil, user: nil, acting_for: nil, region: nil, - team: nil, usage_categories: []) + def initialize(url: nil, customer_id: nil, app_id: nil, api_key: nil, api_secret: nil, + private_key: nil, token: nil, user_id: nil, authenticate: nil, user: nil, + acting_for: nil, region: nil, team: nil, usage_categories: []) @url = locate(present(url), present(region)).chomp("/") @customer_id = customer_id || ENV.fetch(CUSTOMER_ENV, "") + @app_id = app_id.to_s + @private_key = private_key.to_s.strip # Naming a customer is choosing how a router with nothing in front of it is reached, # and a key that happens to be in the environment does not overrule the choice. @api_key = api_key || (@customer_id.empty? ? ENV.fetch(API_KEY_ENV, "") : "") @token = token.to_s # A token handed in is the caller's answer to who they are, so an ambient secret does # not turn a client built for a user into a backend. - @api_secret = api_secret || (@token.empty? ? ENV.fetch(API_SECRET_ENV, "") : "") + @api_secret = api_secret || (@token.empty? && @private_key.empty? ? ENV.fetch(API_SECRET_ENV, "") : "") @authenticate = if authenticate.nil? flag(ENV.fetch(AUTHENTICATE_ENV, nil)) || hosted?(@url) else @@ -100,7 +102,11 @@ def initialize(url: nil, customer_id: nil, api_key: nil, api_secret: nil, token: # Only a server-side caller reaches the operations the spec does not mark client # accessible. Worth asking before a call rather than reading a 403 afterwards. def server_side? - !@api_secret.empty? || (@api_key.empty? && !@customer_id.empty?) + !@private_key.empty? || !@api_secret.empty? || (@api_key.empty? && !@customer_id.empty?) + end + + def ed25519? + !@private_key.empty? end def authenticate? @@ -153,7 +159,7 @@ def headers(acting_for: nil) said = credentials(acting) said["X-Stream-User-Id"] = acting unless acting.empty? categories = named_categories - said[USAGE_CATEGORIES_HEADER] = categories.join(",") unless @authenticate || categories.empty? + said[USAGE_CATEGORIES_HEADER] = categories.join(",") unless @private_key != "" || @authenticate || categories.empty? said end @@ -200,7 +206,30 @@ def self.checked_categories(team, categories) # The WebSocket URL for a path on the router. Credentials travel as headers. def socket_url(path) - @url.sub(/\Ahttp/, "ws") + path + target = @url.sub(/\Ahttp/, "ws") + path + return target unless !@private_key.empty? && !@api_key.empty? + + sep = target.include?("?") ? "&" : "?" + "#{target}#{sep}api_key=#{URI.encode_www_form_component(@api_key)}" + end + + # Signs an EdDSA (Ed25519) JWT using a PEM-encoded PKCS#8 private key. + def self.sign_ed25519(claims, private_key_pem, validity: TOKEN_VALIDITY) + key = parse_ed25519_key(private_key_pem) + issued = Time.now.to_i + header = encode(JSON.generate({ alg: "EdDSA", typ: "JWT" })) + payload = encode(JSON.generate({ iat: issued, exp: issued + validity }.merge(claims))) + signing = "#{header}.#{payload}" + "#{signing}.#{encode(key.sign(nil, signing))}" + end + + def self.parse_ed25519_key(private_key_pem) + key = OpenSSL::PKey.read(private_key_pem.to_s) + raise ConfigurationError, "private_key must be an Ed25519 private key" unless key.oid == "ED25519" + + key + rescue OpenSSL::PKey::PKeyError => e + raise ConfigurationError, "invalid Ed25519 private_key: #{e.message}" end # Signs a Stream token: HS256 out of OpenSSL rather than a JWT gem, since issuing one @@ -256,6 +285,7 @@ def hosted?(url) end def credentials(acting) + return { "Authorization" => "Bearer #{ed25519_token}" } unless @private_key.empty? return { CUSTOMER_HEADER => @customer_id } if @api_key.empty? if @authenticate @@ -278,6 +308,10 @@ def credentials(acting) end def validate + unless @private_key.empty? + Backend.parse_ed25519_key(@private_key) + return + end if @authenticate && @api_key.empty? raise ConfigurationError, "a router behind the proxy is reached with a credential; pass api_key or set #{API_KEY_ENV}" @@ -306,6 +340,21 @@ def proxy_token(acting) sign(server: true) end + def ed25519_token + claims = {} + claims[:customer_id] = @customer_id unless @customer_id.empty? + claims[:app_id] = @app_id unless @app_id.empty? + if @user_id.empty? + claims[:kind] = "server" + else + claims[:kind] = "authenticated" + claims[:user_id] = @user_id + end + claims[:team] = @team if @team + claims[:usage_categories] = @usage_categories unless @usage_categories.empty? + Backend.sign_ed25519(claims, @private_key) + end + # A token naming this backend's team and usage categories, each only when there is one. def sign(claims) claims[:team] = @team if @team diff --git a/sdks/ruby/lib/getstream/vision_agents/client.rb b/sdks/ruby/lib/getstream/vision_agents/client.rb index ae0d551feb..21fb1b69f5 100644 --- a/sdks/ruby/lib/getstream/vision_agents/client.rb +++ b/sdks/ruby/lib/getstream/vision_agents/client.rb @@ -190,6 +190,9 @@ def request(method, template, path:, query:, user_id:, body: nil, resend: true) operation = operation_for(method, template) raise ConfigurationError, "#{template} is a socket; open it with #socket" if operation[:socket] + if @backend.ed25519? && !@backend.api_key.empty? + query = query.merge("api_key" => @backend.api_key) + end target = URI(@backend.url + expand(operation, template, path, query)) payload = encode_body(operation, body) started = Net::HTTP.const_get(method.to_s.capitalize).new(target) diff --git a/sdks/ruby/test/ed25519_test.rb b/sdks/ruby/test/ed25519_test.rb new file mode 100644 index 0000000000..52909d884e --- /dev/null +++ b/sdks/ruby/test/ed25519_test.rb @@ -0,0 +1,60 @@ +# frozen_string_literal: true + +require "base64" +require "json" +require "minitest/autorun" +require "openssl" +require "uri" +require_relative "../lib/getstream/vision_agents" + +class Ed25519BackendTest < Minitest::Test + def setup + @key = OpenSSL::PKey.generate_key("ED25519") + @pem = @key.private_to_pem + end + + def verify_bearer(auth_header) + assert auth_header&.start_with?("Bearer "), "expected Bearer header" + raw_header, raw_payload, raw_sig = auth_header.delete_prefix("Bearer ").split(".") + header = JSON.parse(Base64.urlsafe_decode64(raw_header)) + assert_equal "EdDSA", header["alg"] + assert @key.verify(nil, Base64.urlsafe_decode64(raw_sig), "#{raw_header}.#{raw_payload}") + JSON.parse(Base64.urlsafe_decode64(raw_payload)) + end + + def test_invalid_private_key_is_refused + assert_raises(GetStream::VisionAgents::ConfigurationError) do + GetStream::VisionAgents::Backend.new(url: "http://localhost:8080", private_key: "not-a-key") + end + end + + def test_server_and_client_credentials_and_socket_url + backend = GetStream::VisionAgents::Backend.new( + url: "https://router.example.com", + api_key: "pub-key", + customer_id: "org-1", + app_id: "app-1", + private_key: @pem, + team: "sales", + usage_categories: ["support"] + ) + + assert backend.server_side? + headers = backend.headers + refute headers.key?("X-Api-Key") + refute headers.key?("api_key") + + claims = verify_bearer(headers["Authorization"]) + assert_equal "org-1", claims["customer_id"] + assert_equal "app-1", claims["app_id"] + assert_equal "server", claims["kind"] + assert_equal "sales", claims["team"] + assert_equal ["support"], claims["usage_categories"] + + ws = URI(backend.socket_url("/v1/dispatch?capacity=4")) + params = URI.decode_www_form(ws.query).to_h + assert_equal "wss", ws.scheme + assert_equal "pub-key", params["api_key"] + assert_equal "4", params["capacity"] + end +end diff --git a/sdks/rust/Cargo.lock b/sdks/rust/Cargo.lock index 7dadfcc229..f845190879 100644 --- a/sdks/rust/Cargo.lock +++ b/sdks/rust/Cargo.lock @@ -2122,6 +2122,7 @@ dependencies = [ "rand 0.10.3", "rcgen", "reqwest", + "ring", "schemars 1.2.3", "serde", "serde_json", diff --git a/sdks/rust/Cargo.toml b/sdks/rust/Cargo.toml index 719b99b6ff..629af86ea1 100644 --- a/sdks/rust/Cargo.toml +++ b/sdks/rust/Cargo.toml @@ -28,6 +28,7 @@ thiserror = "2" yaml-rust2 = "0.13" md-5 = "0.11" hmac = "0.13" +ring = "0.17" sha2 = "0.11" base64 = "0.23" url = "2" diff --git a/sdks/rust/src/backend.rs b/sdks/rust/src/backend.rs index ebcee6d02e..ca00d135df 100644 --- a/sdks/rust/src/backend.rs +++ b/sdks/rust/src/backend.rs @@ -1,8 +1,9 @@ use std::time::{SystemTime, UNIX_EPOCH}; use base64::Engine as _; -use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use hmac::{Hmac, KeyInit, Mac}; +use ring::signature::Ed25519KeyPair; use serde_json::{Value, json}; use sha2::Sha256; @@ -158,6 +159,9 @@ pub struct ClientOptions { /// Who the work is billed to, taken at face value, for a router with no keys in front /// of it. Falls back to `STREAM_ACCELERATION_CUSTOMER_ID`. pub customer_id: Option, + /// The app claim written into Ed25519 JWTs when talking directly to a router without a + /// gateway (in `api_key` mode the router resolves it from `api_key` instead). + pub app_id: Option, /// The public half of a Stream credential. Falls back to `STREAM_API_KEY`, unless a /// customer id was named: naming one is choosing how the router is reached, and a key /// lying about in the environment does not overrule the choice. @@ -165,6 +169,9 @@ pub struct ClientOptions { /// The secret belonging to that key, which is what makes this a backend. Falls back to /// `STREAM_API_SECRET`, unless a token was handed in. pub api_secret: Option, + /// PEM-encoded PKCS#8 Ed25519 private key used to sign EdDSA JWTs. + /// When set, requests send `Authorization: Bearer ` and `api_key` in the query string. + pub private_key: Option, /// A token minted for `user_id` to hold, in place of the secret. pub token: Option, /// The end user this client acts for. With a secret it is sent as `X-Stream-User-Id`, so @@ -193,8 +200,10 @@ pub struct ClientOptions { pub(crate) struct Backend { pub url: String, pub customer_id: String, + pub app_id: String, pub api_key: String, pub api_secret: String, + pub private_key: String, pub token: String, pub user_id: String, /// The end user a server credential speaks for. Unlike `user_id` it never becomes a user @@ -239,12 +248,22 @@ impl Backend { env(API_KEY_ENV).unwrap_or_default() } }); + let app_id = options.app_id.clone().unwrap_or_default(); + let private_key = options + .private_key + .as_deref() + .map(str::trim) + .unwrap_or_default() + .to_string(); + if !private_key.is_empty() { + ed25519_keypair(&private_key)?; + } let token = options.token.clone().unwrap_or_default(); // A token that was handed in is the caller's answer to who they are, so an ambient // secret does not overrule it: otherwise a client built the way a device builds one // turns into a backend in any process that happens to hold the secret. let api_secret = options.api_secret.clone().unwrap_or_else(|| { - if token.is_empty() { + if token.is_empty() && private_key.is_empty() { env(API_SECRET_ENV).unwrap_or_default() } else { String::new() @@ -255,21 +274,23 @@ impl Backend { .authenticate .unwrap_or_else(|| flag(env(AUTHENTICATE_ENV)) || hosted(&url)); - if authenticate && api_key.is_empty() { - return Err(Error::configuration(format!( - "a router behind the proxy is reached with a credential; pass api_key or set {API_KEY_ENV}" - ))); - } - if api_key.is_empty() && customer_id.is_empty() { - return Err(Error::configuration(format!( - "who is calling is not set; pass customer_id or set {CUSTOMER_ENV} for a router that \ - trusts one, or api_key with either api_secret or token" - ))); - } - if !api_key.is_empty() && api_secret.is_empty() && token.is_empty() { - return Err(Error::configuration( - "api_key needs the secret it belongs to, or a token minted with it", - )); + if private_key.is_empty() { + if authenticate && api_key.is_empty() { + return Err(Error::configuration(format!( + "a router behind the proxy is reached with a credential; pass api_key or set {API_KEY_ENV}" + ))); + } + if api_key.is_empty() && customer_id.is_empty() { + return Err(Error::configuration(format!( + "who is calling is not set; pass customer_id or set {CUSTOMER_ENV} for a router that \ + trusts one, or api_key with either api_secret or token" + ))); + } + if !api_key.is_empty() && api_secret.is_empty() && token.is_empty() { + return Err(Error::configuration( + "api_key needs the secret it belongs to, or a token minted with it", + )); + } } let team = options.team.clone().filter(|team| !team.is_empty()); let usage_categories = checked_categories(team.as_deref(), &options.usage_categories)?; @@ -283,8 +304,10 @@ impl Backend { Ok(Backend { url, customer_id, + app_id, api_key, api_secret, + private_key, token, user_id: options.user_id.clone().unwrap_or_default(), acting_for: String::new(), @@ -296,7 +319,13 @@ impl Backend { /// Whether this speaks for a process the customer runs rather than for a device. pub fn server_side(&self) -> bool { - !self.api_secret.is_empty() || (self.api_key.is_empty() && !self.customer_id.is_empty()) + !self.private_key.is_empty() + || !self.api_secret.is_empty() + || (self.api_key.is_empty() && !self.customer_id.is_empty()) + } + + pub fn uses_ed25519(&self) -> bool { + !self.private_key.is_empty() } /// What every request and socket handshake carries. @@ -309,7 +338,10 @@ impl Backend { if !self.acting_for.is_empty() { headers.push(("X-Stream-User-Id", self.acting_for.clone())); } - if !self.authenticate && (self.team.is_some() || !self.usage_categories.is_empty()) { + if self.private_key.is_empty() + && !self.authenticate + && (self.team.is_some() || !self.usage_categories.is_empty()) + { let mut named = self.usage_categories.clone(); named.extend(self.team.iter().map(|team| format!("{TEAM_PREFIX}{team}"))); named.sort(); @@ -324,6 +356,12 @@ impl Backend { } fn credentials(&self) -> Result> { + if !self.private_key.is_empty() { + return Ok(vec![( + "Authorization", + format!("Bearer {}", self.ed25519_token()?), + )]); + } if self.api_key.is_empty() { return Ok(vec![("X-Customer-Id", self.customer_id.clone())]); } @@ -360,13 +398,41 @@ impl Backend { /// The WebSocket URL for a path on the router. pub fn socket_url(&self, path: &str) -> String { - if let Some(rest) = self.url.strip_prefix("https://") { - return format!("wss://{rest}{path}"); + let mut target = if let Some(rest) = self.url.strip_prefix("https://") { + format!("wss://{rest}{path}") + } else if let Some(rest) = self.url.strip_prefix("http://") { + format!("ws://{rest}{path}") + } else { + format!("{}{path}", self.url) + }; + if !self.private_key.is_empty() && !self.api_key.is_empty() { + let sep = if target.contains('?') { '&' } else { '?' }; + target.push(sep); + target.push_str("api_key="); + target.push_str(&self.api_key); + } + target + } + + fn ed25519_token(&self) -> Result { + let mut claims = serde_json::Map::new(); + if !self.customer_id.is_empty() { + claims.insert("customer_id".into(), json!(self.customer_id)); } - if let Some(rest) = self.url.strip_prefix("http://") { - return format!("ws://{rest}{path}"); + if !self.app_id.is_empty() { + claims.insert("app_id".into(), json!(self.app_id)); } - format!("{}{path}", self.url) + if self.user_id.is_empty() { + claims.insert("kind".into(), json!("server")); + } else { + claims.insert("kind".into(), json!("authenticated")); + claims.insert("user_id".into(), json!(self.user_id)); + } + sign_ed25519( + self.claimed(Value::Object(claims)), + &self.private_key, + TOKEN_VALIDITY_SECONDS, + ) } /// The token the proxy is given, which names a user where there is one: the proxy has @@ -423,6 +489,42 @@ pub fn sign_for(claims: Value, secret: &str, validity_seconds: u64) -> Result Result { + let body: String = pem + .lines() + .filter(|line| !line.starts_with("-----")) + .map(str::trim) + .collect(); + let der = STANDARD + .decode(body) + .map_err(|_| Error::configuration("invalid Ed25519 PEM private_key"))?; + Ed25519KeyPair::from_pkcs8_maybe_unchecked(&der) + .map_err(|_| Error::configuration("private_key must be a PKCS#8 Ed25519 private key")) +} + +/// Signs an EdDSA (Ed25519) JWT using a PEM-encoded PKCS#8 private key. +pub fn sign_ed25519(claims: Value, private_key_pem: &str, validity_seconds: u64) -> Result { + let pair = ed25519_keypair(private_key_pem)?; + let issued = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + let mut payload = json!({"iat": issued, "exp": issued + validity_seconds}); + if let (Some(payload), Value::Object(claims)) = (payload.as_object_mut(), claims) { + payload.extend(claims); + } + let signing = format!( + "{}.{}", + URL_SAFE_NO_PAD.encode(br#"{"alg":"EdDSA","typ":"JWT"}"#), + URL_SAFE_NO_PAD.encode(payload.to_string()) + ); + let sig = pair.sign(signing.as_bytes()); + Ok(format!( + "{signing}.{}", + URL_SAFE_NO_PAD.encode(sig.as_ref()) + )) +} + pub(crate) fn env(name: &str) -> Option { std::env::var(name).ok().filter(|value| !value.is_empty()) } @@ -581,4 +683,75 @@ mod tests { } } } + + #[test] + fn ed25519_signs_bearer_jwt_and_appends_api_key_on_socket_url() { + use ring::rand::SystemRandom; + use ring::signature::{ED25519, KeyPair, UnparsedPublicKey}; + + let doc = Ed25519KeyPair::generate_pkcs8(&SystemRandom::new()).unwrap(); + let pair = Ed25519KeyPair::from_pkcs8(doc.as_ref()).unwrap(); + let pem = format!( + "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----", + STANDARD.encode(doc.as_ref()) + ); + + let backend = Backend::with_env( + &ClientOptions { + url: Some("https://router.example.com".into()), + api_key: Some("pub-key".into()), + customer_id: Some("org-1".into()), + app_id: Some("app-1".into()), + private_key: Some(pem), + team: Some("sales".into()), + usage_categories: vec!["support".into()], + ..Default::default() + }, + environment(&[]), + ) + .unwrap(); + + assert!(backend.server_side()); + let headers = backend.headers().unwrap(); + let auth = headers + .iter() + .find(|(k, _)| *k == "Authorization") + .map(|(_, v)| v.as_str()) + .unwrap(); + let token = auth.strip_prefix("Bearer ").unwrap(); + let parts: Vec<&str> = token.split('.').collect(); + assert_eq!(parts.len(), 3); + + let pub_key = UnparsedPublicKey::new(&ED25519, pair.public_key().as_ref()); + let sig = URL_SAFE_NO_PAD.decode(parts[2]).unwrap(); + pub_key + .verify(format!("{}.{}", parts[0], parts[1]).as_bytes(), &sig) + .unwrap(); + + let claims: Value = + serde_json::from_slice(&URL_SAFE_NO_PAD.decode(parts[1]).unwrap()).unwrap(); + assert_eq!(claims["customer_id"], "org-1"); + assert_eq!(claims["app_id"], "app-1"); + assert_eq!(claims["kind"], "server"); + assert_eq!(claims["team"], "sales"); + assert_eq!(claims["usage_categories"], json!(["support"])); + + assert_eq!( + backend.socket_url("/v1/dispatch?capacity=4"), + "wss://router.example.com/v1/dispatch?capacity=4&api_key=pub-key" + ); + } + + #[test] + fn invalid_ed25519_private_key_is_refused() { + let refused = Backend::with_env( + &ClientOptions { + url: Some("http://localhost:8080".into()), + private_key: Some("not-a-key".into()), + ..Default::default() + }, + environment(&[]), + ); + assert!(matches!(refused, Err(Error::Configuration(_)))); + } } diff --git a/sdks/rust/src/client.rs b/sdks/rust/src/client.rs index ac9ad49818..90d23fa95b 100644 --- a/sdks/rust/src/client.rs +++ b/sdks/rust/src/client.rs @@ -102,9 +102,11 @@ impl Client { url: Some(backend.url.clone()), region: None, customer_id: Some(backend.customer_id.clone()), + app_id: None, api_key: Some(backend.api_key.clone()), // A token is the whole credential, so holding one stops this being a backend. api_secret: Some(String::new()), + private_key: None, token: Some(token.to_string()), user_id: Some(user_id.to_string()), authenticate: Some(backend.authenticate), @@ -302,6 +304,9 @@ impl Client { for (name, value) in self.inner.backend.headers()? { request = request.header(name, value); } + if self.inner.backend.uses_ed25519() && !self.inner.backend.api_key.is_empty() { + request = request.query(&[("api_key", self.inner.backend.api_key.as_str())]); + } if let Some(query) = query { request = request.query(query); } diff --git a/uv.lock b/uv.lock index c4da91d33c..7706dd9349 100644 --- a/uv.lock +++ b/uv.lock @@ -7438,6 +7438,7 @@ source = { editable = "plugins/stream" } dependencies = [ { name = "aiohttp" }, { name = "attrs" }, + { name = "cryptography" }, { name = "httpx" }, { name = "pyyaml" }, { name = "vision-agents" }, @@ -7453,6 +7454,7 @@ dev = [ requires-dist = [ { name = "aiohttp", specifier = ">=3.10" }, { name = "attrs", specifier = ">=23.2" }, + { name = "cryptography", specifier = ">=44.0.0" }, { name = "httpx", specifier = ">=0.27" }, { name = "pyyaml", specifier = ">=6.0" }, { name = "vision-agents", editable = "sdks/python" },